根据:http://www.cplusplus.com/doc/tutorial/classes/
析构函数实现与构造函数相反的功能。当一个对象被销毁时,它会被自动调用,因为它的存在范围已经结束(例如,如果它被定义为函数中的局部对象并且函数结束)或者因为它是一个动态分配的对象并被释放使用运算符删除。
示例代码:
class Something
{
public:
Something() {cout << "construction called" << endl; }
~Something() { cout << "destruction called" << endl; }
};
void foo(){
Something *ob = new Something();
}
int _tmain(int argc, _TCHAR* argv[])
{
foo();
}
最佳答案
确实如此,但是您在动态内存 中分配对象,这意味着它不会被破坏,直到您调用delete
。
because it is an object dynamically assigned and it is released using the operator delete.
你永远不会调用 delete。因此内存泄漏和未调用的析构函数:
void foo(){
Something *ob = new Something();
delete ob;
}
要么这样,要么简单地在自动内存中分配对象:
void foo(){
Something ob;
}
或者将内存管理委托(delegate)给智能指针。
关于c++ - 未调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12587774/