3

I have a class inside a class, nested class

class A {
 public:
 int a;
 int b;
  class B {
    int c;
    int d;
  }
}

In the process, I allocate the class B's object pointer in heap.

   B *bobj = new B();
   A *a;
   auto_ptr<A> A1(new A());
   a = A1.release();

Does deleting the a, delete bobj as well??

delete a;

or should we explicitly delete the sub class pointer as well?

This is in a code not written by me, I had put the logs at all alloc and deallocs and I see that B *bobj = new B(), for this there is no delete and for A's object ptr there is a delete. And yet there is no memory leak.That is why I got a doubt what happens in this scenario.

4

4 回答 4

9

我想你在这里有点困惑。如果你有一个 type 的对象A,它里面没有B对象。它只有两个intsab。您的类B只是在内部声明为嵌套类A- 类似于在命名空间中声明它。它必须A::B从类外引用(并且必须public这样做)。

在您提供的示例代码中B *bobj = new B(); A *a;,您甚至没有创建A对象。我想你的意思是这个(假设你 make B public):

A::B *bobj = new A::B();
A *a = new A();

两者abobj都是完全独立的对象。他们彼此没有任何关系。你必须对delete他们两个。

相反,如果您这样做了:

class B {
  int c;
  int d;
};

class A {
  int a;
  B b;
};

现在类类型的对象A有一个名为的成员b,其类型为B。该b成员是任何类型对象的一部分A。所以如果你这样做A* a = new A();,你会得到一个里面A有一个对象的对象。B你必须只做delete a;.

黄金法则:只有delete你已经new编辑过的东西。

于 2013-02-26T12:49:42.893 回答
3

您编写代码的方式class B是 中的嵌套类型class A,但 中不class B包含class A的实例,这意味着必须单独管理实例化(因此销毁)。所以是的,delete如果你们new两个都需要。

于 2013-02-26T12:48:39.773 回答
3

这取决于你的析构函数在做什么。如果A包含类型的指针B并且在A该指针的析构函数中被释放 - 是的。如果A不包含类型指针B和/或 inA的析构函数指针B未释放 - 您应该手动释放它。

于 2013-02-26T12:49:34.340 回答
2

In short, C++ doesn't automatically delete object pointers (without specialize auto-pointers etc.). So, explicitly delete them in your program.

delete a; call destructor of A class. You can write code to delete B's object inside destructor.

于 2013-02-26T12:48:32.923 回答