[ 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.
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, 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.
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:
Has simple type members which are not pointers.
Has class members with properly defined destructors.
Is a certain kind of Qt class satisfying certain conditions.[27]
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.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |