Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C++ destructor always or only sometimes call data member destructors?

Tags:

c++

destructor

I'm trying to validate my understanding of C++ destructors.

I've read many times that C++ supplies a default destructor if I don't write one myself. But does this mean that if I DO write a destructor that the compiler WON'T still provide the default cleanup of stack-allocated class fields?

My hunch is that the only sane behavior would be that all class fields are destroyed no matter what, whether I provide my own destructor or not. In which case the statement I've read so many times is actually a little misleading and could be better stated as:

"Whether or not you write your own destructor, the C++ compiler always writes a default destructor-like sequence to deallocate the member variables of your class. You may then specify additional deallocations or other tasks as needed by defining your own destructor"

Is this correct?

like image 573
Magnus Avatar asked Nov 09 '13 03:11

Magnus


Video Answer


2 Answers

When an object is cleaned up in C++, the language will

  • First call the destructor for the class, then
  • Call the destructors for all the fields of the class.

(This assumes no inheritance; if there's inheritance, the base class is then destroyed by recursively following this same procedure). Consequently, the destructor code that you write is just custom cleanup code that you'd like to do in addition to the normal cleanup code for individual data members. You won't somehow "lose" the destructors for those objects being called as normal.

Hope this helps!

like image 67
templatetypedef Avatar answered Oct 16 '22 13:10

templatetypedef


Yes -- any object contained within your object will be destroyed as part of destroying your object, even if/though your destructor does nothing to destroy them.

In fact, your destructor won't normally do anything to destroy objects contained within the object; what it typically does is destroy objects that are remotely owned via something in the object (e.g., a pointer to an object, a handle to a network or database connection, etc.)

The only exception to this that's common at all is if your object contains a buffer of some sort, and you've used placement new to construct something into that buffer. If you use placement new, you normally plan on directly invoking the dtor as well. [Note that "common" is probably overstating how often you see/use this--it's really quite uncommon, but the other possibilities are much rarer still.]

like image 43
Jerry Coffin Avatar answered Oct 16 '22 13:10

Jerry Coffin