如何删除分配给基类的指针?

时间:2012-06-25 08:27:12

标签: c++ inheritance delete-operator

我有一个基类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( )对象的内存?

3 个答案:

答案 0 :(得分:3)

  

“删除lBaseobj”是否释放分配给lBaseobj的内存   也可以是新的A()对象。

来自您的示例

在您泄漏内存之下,因为A未被删除:

...
lBaseobj->func1( );  // where is delete lBaseObj; ??
lBaseobj = new B( );
...

下面没问题,因为A::~A()是虚拟的:

...
lBaseobj->func2( );
delete lBaseobj;

答案 1 :(得分:2)

不,初始对象不会被破坏:

A* lBaseobj = new A ( );
lBaseobj->func1( );
delete lBaseobj; // call delete here
lBaseobj = new B( );

您应遵守的经验法则:对于每new delete,应该有new[],对于每delete[],应该有new

在您的代码中,您有2 delete个,但只有1 {{1}}。

答案 2 :(得分:1)

如果使用智能指针,内存不会泄露:

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()