2.8.  Destructors

[ fromfile: destructors.xml id: destructors ]

[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.

[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.



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