删除调用析构函数吗? [英] Does delete call the destructor?

查看:135
本文介绍了删除调用析构函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(A),它使用堆内存分配为其中的一个字段。类A被实例化并作为指针字段存储在另一个类(B)中。

I have an class (A) which uses a heap memory allocation for one of it's fields. Class A is instantiated and stored as a pointer field in another class (B).

当我完成对象B时,我调用delete,析构函数...但是这是否也调用了A类中的析构函数?

When I'm done with object B, I call delete, which I assume calls the destructor... But does this call the destructor in class A as well?

(如果不正确,请修改):

From the answers, I take that (please edit if incorrect):


  1. delete B的实例调用B ::〜B();

  2. 调用 A ::〜A(); 明确删除 c $ c> A的所有堆分配的成员变量;

  3. 最后,存储所述B实例的内存块返回堆 - 当 new 使用,它首先在堆上分配一块内存,然后调用构造函数来初始化它,现在所有析构函数都被调用完成对象后,对象所在的块返回堆。

  1. delete instance of B calls B::~B();
  2. which calls A::~A();
  3. and A::~A should explicitly delete all heap-allocated member variables of A;
  4. and finally the memory block storing said instance of B is returned to the heap - when new was used, it first allocated a block of memory on heap, then invoked constructors to initialize it, now after all destructors have been invoked to finalize the object the block where the object resided is returned to the heap.


推荐答案

A的析构函数将在其生存期结束时运行。如果你想要释放它的内存并运行析构函数,你必须删除它,如果它在堆上分配。如果它在堆栈上分配,这会自动发生(即当它超出范围时;参见RAII)。如果它是一个类的成员(不是一个指针,而是一个完整的成员),那么这将发生在包含对象被销毁时。

The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.

class A
{
    char *someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { delete[] someHeapMemory; }
};

class B
{
    A* APtr;
public:
    B() : APtr(new A()) {}
    ~B() { delete APtr; }
};

class C
{
    A Amember;
public:
    C() : Amember() {}
    ~C() {} // A is freed / destructed automatically.
};

int main()
{
    B* BPtr = new B();
    delete BPtr; // Calls ~B() which calls ~A() 
    C *CPtr = new C();
    delete CPtr;
    B b;
    C c;
} // b and c are freed/destructed automatically

删除和删除[]。

auto_ptr ,并且不需要删除(或者确实能够使用) unique_ptr shared_ptr 等都是伟大的使这个生命周期管理更容易:

auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:

class A
{
    shared_array<char> someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { } // someHeapMemory is delete[]d automatically
};

class B
{
    shared_ptr<A> APtr;
public:
    B() : APtr(new A()) {}
    ~B() {  } // APtr is deleted automatically
};

int main()
{
    shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically

这篇关于删除调用析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆