c++ - 析构函数必须做与构造函数对静态成员所做的相反的事情吗?

标签 c++ destructor static-members

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

最佳答案

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

关于c++ - 析构函数必须做与构造函数对静态成员所做的相反的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344777/

相关文章:

c++ - 双链表出现错误 'pointer being freed was not allocated'

c++ - 我们什么时候需要定义析构函数?

c++ - 使用 gcc 调用纯虚函数时出现链接器错误

c++ - 为什么 WinDbg 无法使用 Service Pack 2 x86 零售符号下载从 Windows Server 2003 加载符号?

c++ - 将 NanoGUI 添加到 OpenGL 项目

c++ - 为什么在此代码中忽略了析构函数?

C++在不创建新对象的情况下获取类成员的默认值

c++ - Visual Studio 的隐式静态成员初始化失败

F#代码组织: types & modules

c++ - 字符串类型数组的指针运算,C++是如何处理的?