为什么C ++默认析构函数不销毁我的对象? [英] Why doesn't the C++ default destructor destroy my objects?
问题描述
C ++规范说,默认析构函数删除所有非静态成员。
The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can't manage to achieve that.
我有这个:
class N {
public:
~N() {
std::cout << "Destroying object of type N";
}
};
class M {
public:
M() {
n = new N;
}
// ~M() { //this should happen by default
// delete n;
// }
private:
N* n;
};
然后这应该打印给定的消息,但它不:
Then this should print the given message, but it doesn't:
M* m = new M();
delete m; //this should invoke the default destructor
推荐答案
认为对象 n
指向应该在默认情况下删除?默认析构函数销毁指针,而不是指向它。
What makes you think the object n
points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to.
编辑:我会看看我是否可以更清楚一点。
I'll see if I can make this a little more clear.
如果你有一个局部指针,并且它超出范围,你会指望它指向的对象被销毁吗?
If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed?
{
Thing* t = new Thing;
// do some stuff here
// no "delete t;"
}
t
指针被清理,但 Thing
它指向是不是。这是一个泄漏。基本上同样的事情发生在你的班上。
The t
pointer is cleaned up, but the Thing
it points to is not. This is a leak. Essentially the same thing is happening in your class.
这篇关于为什么C ++默认析构函数不销毁我的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!