在 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
定义了一个复制操作。因此,我预计 Obj
的 SubObj
成员不会被销毁,因为 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 memberpos
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/