析构函数如何删除嵌套的堆栈类型?

时间:2013-04-21 21:15:24

标签: c++

示例:

class A
{
   char * data;
   ...
   A(){data = new char[50];}
   ~A(){delete [] data;}
};

class B
{
   A a;

   B();
   // default destructor
}

void foo()
{
   B b;
}

int main()
{
   foo();

   // "A.data" still in the heap or no?
}

这个程序是正确的,并且“A.data”将在main中的foo()之后被删除,或者是否仍然存在于堆中?

3 个答案:

答案 0 :(得分:5)

是的,它将被删除,您需要使用delete[]数组。另外你应该记住Rule of three

答案 1 :(得分:3)

~A(){delete data;}

应该是

~A()
{
    delete[] data;
 }
 //remove the dynamic array

在当前代码中,当主要退出时,它将调用析构函数释放内存,并且不会存在于堆中。

答案 2 :(得分:2)

当一个对象被破坏时,编译器会自动销毁所有类的非指针数据成员。因此,当您的B b变量超出范围时,编译器会自动销毁它,这反过来会破坏A a数据成员,因为它不是指针,它会调用~A()来释放数组