1

I have a struct say A, which has a member say B *C. I dynamically create t1 = new A, which internally dynamically creates C = new B.

Now to free memory allocated to C, is delete t1 sufficient? Or I should have delete t1 followed by delete t1->C ?

Also is there a better way to do it in one shot?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 4
    You give `A` a destructor that takes care of releasing all its resources. – juanchopanza Jul 08 '14 at 12:15
  • You have (I assume) created a constructor that allocates `C`, similarly you should call `delete C` in your destructor – YePhIcK Jul 08 '14 at 12:16
  • 3
    Better yet, use a `shared_ptr C` or a `unique_ptr C` -- then *their* destructors automatically delete them (if and only if this is necessary) when the containing object is destroyed -- so you can't forget to! – j_random_hacker Jul 08 '14 at 12:17
  • 1
    why do you want to do it? The simplest one shot solution is nice c++, and it is `class B {}; class A { B c; };`. – Dmitry Ledentsov Jul 08 '14 at 12:22
  • 2
    Related questions: [What is meant by Resource Acquisition is Initialization (RAII)?](http://stackoverflow.com/q/2321511/96780) and [Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)](http://stackoverflow.com/q/712639/96780). In particular what you want is to use destructors semantics to manage resources (UDSTMR), see [this answer](http://stackoverflow.com/a/712649/96780). – Daniel Daranas Jul 08 '14 at 12:22

3 Answers3

1

So let's clear up things. A has B* C; which is supposed to store pointer to an object on the free store (this is not obvious at all, it can point to anything).

Now in A's destructor you will need to delete your pointer to C, or you'll get a memory leak.

Zsolt
  • 582
  • 2
  • 5
1

Deleting t1 only is not sufficient. You need to make sure that t1->C is deleted as well. But

should have delete t1 followed by delete t1->C

The other way round! When you deleted t1, you no longer can access t1->C. To get rid of such issues completely never use raw pointers as described in your questions. Use smart pointers and then delete will be executed automatically for you in the required order.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
1

Each new call makes a new memory allocation and each of them should reallocate. If you don't memory leak problem occurs.

A good solution to this problem for classses is making its into A's destructor.

~A::A(){
 delete this->C;
}
eakgul
  • 3,658
  • 21
  • 33