Natko Kraševac
Natko Kraševac

Reputation: 111

How to delete complete object from heap in C++?

Say I have something like this:

a = new A(); 
a->b = new B(); 
a->b->c = new C();

If I call:

delete(a)

Would it also delete b and c from memory? How can I be sure that all of them are gone?

This is a question that came up in one of my college classes, made by another student. No more info is given. I guess there is no definitive answer then, because I cannot tell you about the A,B or C destructors

Upvotes: 0

Views: 110

Answers (5)

bames53
bames53

Reputation: 88155

Would it also delete b and c from memory?

Only if A's destructor contains code to explicitly do that or if b is some kind of smart pointer that takes care of it (and can accept the assignment). E.g.:

class A {
  B *b;
  ~A() {
    delete b;
  }
};

How can I be sure that all of them are gone?

Presumably you're asking about best practices for avoiding leaks.

  1. Don't use naked new/delete.
  2. The entity responsible for allocating resources should always also be responsible for deallocating them.
  3. Use RAII.

Upvotes: 0

Xander Kyle Puckett
Xander Kyle Puckett

Reputation: 67

Without any info on how the destructors are defined, then it is true that there is no definitive answer. If there are no explicitly defined destructors, then the default destructors are used, and the code would cause memory leaks. If destructors are properly defined for those classes, then yes, delete(a) should delete b and c from memory.

So in other words, if something like this is defined in the code:

B::~B() { delete c; }
A::~A() { delete b; }

then the answer is yes. If not, the answer is no. If you don't know, then the answer is you can't know.

Upvotes: -1

Slava
Slava

Reputation: 44238

if you have such code in your program:

a = new A(); 
a->b = new B(); 
a->b->c = new C();

you need to (re)learn how to program in C++ properly. Member b of a and member c of b should be initialized by their constructor, not directly. When you write a constructor that use dynamic memory you should immediately think about memory management - either through smart pointers or properly following rule of three/five/zero After you do that there would be no question if memory would be cleaned properly when a is destroyed.

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 11400

Use

class A
{
    std::shared_ptr<B> b;
}

You don't need destructor for A or B. Default ones will do.

Upvotes: 1

M.L.
M.L.

Reputation: 738

  1. Create destructor for A and B.
  2. use smart pointer std::unique_ptr (or std::shared_ptr).

Upvotes: 1

Related Questions