user1065101
user1065101

Reputation:

Deep delete of C++ objects

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?

Upvotes: 1

Views: 1120

Answers (3)

eakgul
eakgul

Reputation: 3698

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;
}

Upvotes: 1

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

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.

Upvotes: 1

Zsolt
Zsolt

Reputation: 582

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.

Upvotes: 1

Related Questions