Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the C++ default destructor destroy my objects?

The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can't manage to achieve that.

I have this:

class N { public:     ~N() {         std::cout << "Destroying object of type N";     } };  class M { public:     M() {         n = new N;     } //  ~M() { //this should happen by default //      delete n; //  } private:     N* n; }; 

Then this should print the given message, but it doesn't:

M* m = new M(); delete m; //this should invoke the default destructor 
like image 429
Oszkar Avatar asked Mar 08 '10 16:03

Oszkar


People also ask

Does destructor destroy the object?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Does Default destructor delete pointers C++?

Default destructors call destructors of member objects, but do NOT delete pointers to objects.

What does default destructor do C++?

Destructor is also a special member function like constructor. Destructor destroys the class objects created by constructor.

Is the destructor automatically in C++?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .


2 Answers

What makes you think the object n points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to.

Edit: I'll see if I can make this a little more clear.

If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed?

{     Thing* t = new Thing;      // do some stuff here      // no "delete t;" } 

The t pointer is cleaned up, but the Thing it points to is not. This is a leak. Essentially the same thing is happening in your class.

like image 178
Fred Larson Avatar answered Sep 28 '22 06:09

Fred Larson


Imagine something like this:

class M { public:     M() { } //  ~M() {        // If this happens by default //      delete n; // then this will delete an arbitrary pointer! //  } private:     N* n; }; 

You're on your own with pointers in C++. No one will automatically delete them for you.

The default destructor will indeed destroy all member objects. But the member object in this case is a pointer itself, not the thing it points to. This might have confused you.

However, if instead of a simple built-in pointer, you will use a smart pointer, the destruction of such a "pointer" (which is actually a class) might trigger the destruction of the object pointed to.

like image 22
P Shved Avatar answered Sep 28 '22 06:09

P Shved