#include <iostream>
using namespace std;
class Base
{
public:
Base ( )
{
cout << "Inside Base constructor" << endl;
}
~Base ( )
{
cout << "Inside Base destructor" << endl;
}
};
class Derived : public Base
{
public:
Derived ( )
{
cout << "Inside Derived constructor" << endl;
}
~Derived ( )
{
cout << "Inside Derived destructor" << endl;
}
};
class Derived2 : public Base
{
public:
static void bogus(Derived2* d)
{
cout << "bogus" << endl;
}
Derived2 ( )
{
cout << "Inside Derived2 constructor" << endl;
}
~Derived2 ( )
{
cout << "Inside Derived2 destructor" << endl;
}
};
int main( )
{
Derived y;
Derived2::bogus( new Derived2 ());
return 0;
}
-
>Inside Base constructor
>Inside Derived constructor
>Inside Base constructor
>Inside Derived2 constructor
>bogus
>Inside Derived destructor
>Inside Base destructor
>Press <RETURN> to close this window...
我在测试一些东西时发现了这种奇怪的行为。当我们在参数字段中创建对象时,为什么不调用析构函数?是否有任何解决方案,是否需要,是否存在内存泄漏?
最佳答案
首先 - 当您使类彼此派生时,您应该确保析构函数是虚拟的
。如果不这样做,则当派生类具有其他成员时可能会发生内存泄漏:
virtual ~Base ( )
{
cout << "Inside Base destructor" << endl;
}
其次 - 当您使用 new
分配内存时,不会在创建的对象上调用析构函数,直到您使用 delete
手动删除它:
int main( )
{
Derived y;
Derived2 *ptr = new Derived2();
Derived2::bogus(ptr);
delete ptr;
return 0;
}
如果您不确定何时删除对象,请使用std::shared_ptr
或在类的析构函数中将其删除,将其作为参数。请注意,shared_ptr
仅适用于 C++11,如果您使用的是旧版本(仍然有很多人使用),请尝试使用 boost 库。
关于c++ - 您如何确保调用 Derived 析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566512/