[ fromfile: destructors.xml id: destructors ]
A destructor, sometimes abbreviated as dtor, is a special member function that automates cleanup actions just before an object is destroyed.
| When is an object destroyed? | |
|---|---|
|
The destructor's name is the classname preceded by the tilde (~) character. It has no return type, and takes no parameters. Therefore, it cannot be overloaded. If the class definition contains no destructor definition, the compiler will supply one that looks like this:
ClassName::~ClassName()
{ }
We look at a less trivial example of a destructor in Section 2.10.
| When do we 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 us to avoid writing code that directly manages dynamic memory. |
You do not need a destructor if your class:
Has simple type members which are not pointers
Has class members with properly defined destructors themsleves
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 nothing to pointer or simple-typed members.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |