我有一个基类A
和一个派生类B
。
class A
{
A();
virtual ~A();
void func1();
virtual void func2();
};
class B : public A
{
B();
~B();
void func2();
};
int main()
{
A* lBaseobj = new A ( );
lBaseobj->func1( );
lBaseobj = new B( );
lBaseobj->func2( );
delete lBaseobj;
return;
}
我的问题是:
delete lBaseobj
是否也会释放lBaseobj
分配给new A( )
对象的内存? 最佳答案
如果使用智能指针,则不会泄漏内存:
std::unique_ptr<A> lBaseobj(new A());
// or: auto lBaseobj = std::make_unique<A>();
lBaseobj->func1();
lBaseobj.reset(new B()); // will delete resources allocated by new A()
lBaseobj->func2();
return 1; // destructor of lBaseobj will delete resources allocated by new B()