0
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,并且您不能更改它的行为?

4

1 回答 1

2

count在调用第一个析构函数后没有任何访问。析构函数完全按照您编写的代码执行,无论是否修改countcount但是除非您以某种方式访问​​,否则您不会看到效果。

于 2012-09-10T02:38:19.017 回答