c++ - 即使没有析构函数,非静态类成员也会被销毁吗?

标签 c++ c++11 destructor

在 Bjarne Stroustrup 的“The C++ Programming Language (4th edition)”第 17.6 节(生成默认操作)中提到了这一点:

If the programmer declares a copy operation, a move operation, or a destructor for a class, no copy operation, move operation, or destructor is generated for that class.

因此,我很困惑为什么要在这个程序中调用 SubObj 析构函数:

#include <iostream>
using namespace std;

class SubObj {
    public:
        ~SubObj() {
            cout << "SubObj Destructor called" << endl;
        }
};

class Obj {
    private:
        SubObj so;

    public:
        Obj() {};
        Obj(const Obj& o) {};
};

int main() {
    Obj();
    cout << "Program end" << endl;
}

当使用 g++ 编译时,我得到以下输出:

$ ./a.out
SubObj Destructor called
Program end

根据我的理解,我预计 Obj 的默认析构函数不会自动生成,因为我为 Obj 定义了一个复制操作。因此,我预计 ObjSubObj 成员不会被销毁,因为 Obj 没有析构函数。

因此,我想知道:即使没有析构函数,对象成员也会自动销毁吗?还是以某种方式为此示例自动生成析构函数?

编辑:

在本书 (17.6.3.4) 的后面,当提到一个例子时,Bjarne 提到:

We defined copy assignment, so we must also define the destructor. That destructor can be =default because all it needs to do is to ensure that the member pos is destyored, which is what would have been done anyway had the copy assignment not been defined.

根据目前的答案,Bjarne 似乎在这个问题上错了。

最佳答案

书中的那句话措辞不当/错误。

当然a destructor is still generated if you provide a copy constructor .否则,您的程序将无法编译。

如果您提供自己的析构函数,则不会生成析构函数。不需要,而且您不能有两个。

此外,无论析构函数做什么,成员都会被销毁。析构函数允许您在对象(和子对象)生命周期的正常规则之上做“额外”的事情。 SubObj 成员永远不会被销毁的风险。

关于c++ - 即使没有析构函数,非静态类成员也会被销毁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55813870/

相关文章:

c++ - 一元和二元否定

c++ - 为什么删除默认参数会破坏此 constexpr 计数器?

c++ - 双倍为真/假

java - 在应用程序级别调整 TCP 数据包大小以实现最大吞吐量

c++ - 在 C++ 中使用继承类流

c++ - c 需要可变参数

c++ - 作为函数指针的模板特化

c++ - 当对象在堆栈上声明时,你能保证析构函数的顺序吗?

c++ - 在 for 循环中使用 push_front 不会将成员永久添加到列表中

c++ - 局部作用域对象按什么顺序被破坏?