0

我有一个基类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( )

4

3 回答 3

3

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

NOYES,从你的例子。

下面你泄漏内存,因为A没有被删除:

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

下面是可以的,因为它A::~A()是虚拟的:

...
lBaseobj->func2( );
delete lBaseobj;
于 2012-06-25T08:29:55.180 回答
2

不,初始对象没有被破坏:

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

您应该遵守一条经验法则:对于每个都new应该有 a delete,对于每个new[]应该有 a delete[]

在您的代码中,您有 2 个new,但只有 1 个delete

于 2012-06-25T08:28:13.950 回答
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()
于 2012-06-25T08:52:05.633 回答