2.8.  Destructors

[ fromfile: destructors.xml id: destructors ]

A destructor, sometimes abbreviated dtor, is a special member function that automates cleanup actions just before an object is destroyed.

[Important] When Is an Object Destroyed?
  • When a local (automatic) object goes out of scope (e.g., when a function call returns).

  • When an object created by the new operator is specifically destroyed by the use of the operator delete.

  • Just before the program terminates, all objects with static storage are destroyed.

The destructor's name is the classname preceded by the tilde (~) character. It has no return type and takes no parameters. Therefore, a class can only have one destructor. If the class definition contains no destructor definition, the compiler supplies one that looks like this:

     ClassName::~ClassName()
        { }

Section 2.9 shows a less trivial example of a destructor.

[Important] When Do You Need to Write a Destructor?

In general, a class that directly manages or shares an external resource (opens a file, opens a network connection, creates a process, etc.) needs to free the resource at some appropriate time. Such classes are usually wrappers that are responsible for object cleanup.

Qt's container classes make it easy for you to avoid writing code that directly manages dynamic memory.

You do not need a destructor if your class:

The default compiler-generated destructor calls the destructors on each of its class members, in the order that they are listed in the class definition, just before the object is destroyed. The default destructor does not delete allocated memory when destroying pointer members.



[27] Such classes are discussed at length starting in Chapter 8.