class A
{
int id;
static int count;
public:
A()
{
count++;
id = count;
cout << "constructor called " << id << endl;
}
~A()
{
//count -=2; /*Keypoint is here. */
/*Uncomment it later. But result doesn't change*/
cout << "destructor called " << id << endl;
}
};
int A::count = 0;
int main()
{
A a[2];
return 0;
}
输出
constructor called 1
constructor called 2
destructor called 2
destructor called 1
问题是:
即使您取消注释//count -=2;
结果仍然相同。
这是否意味着如果构造函数将静态成员递增1,那么析构函数必须将它精确地递减1,并且您无法更改它的行为?
答案 0 :(得分:2)
在调用第一个析构函数后,没有任何东西访问count
。析构函数完全按照您的代码执行操作,或者修改count
。但除非您以某种方式访问count
,否则您将看不到效果。