Destructors

A destructor is a special member function that is called when the lifetime of an object ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime.

# Notes

Calling a destructor directly for an ordinary object, such as a local variable, invokes undefined behavior when the destructor is called again, at the end of scope.

In generic contexts, the destructor call syntax can be used with an object of non-class type; this is known as pseudo-destructor call: see member access operator.

# Example

#include <iostream>
 
struct A
{
    int i;
 
    A(int num) : i(num)
    {
        std::cout << "ctor a" << i << '\n';
    }
 
    ~A()
    {
        std::cout << "dtor a" << i << '\n';
    }
};
 
A a0(0);
 
int main()
{
    A a1(1);
    A* p;
 
    { // nested scope
        A a2(2);
        p = new A(3);
    } // a2 out of scope
 
    delete p; // calls the destructor of a3
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
CWG 193C++98whether automatic objects in a destructor aredestroyed before or after the destruction of theclass’s base and member subobjects was unspecifiedthey are destroyedbefore destroyingthose subobjects
CWG 344C++98the declarator syntax of destructor was defective (had thesame problem as CWG issue 194 and CWG issue 263changed the syntax to a specializedfunction declarator syntax
CWG 1241C++98static members might be destroyedright after destructor executiononly destroy non-static members
CWG 1353C++98the conditions where implicitly-declared destructors areundefined did not consider multi-dimensional array typesconsider these types
CWG 1435C++98the meaning of “class name” in thedeclarator syntax of destructor was unclearchanged the syntax to a specializedfunction declarator syntax
CWG 2180C++98the destructor of class X called thedestructors for X’s virtual direct base classesthose destructors are not called
CWG 2807C++20the declaration specifiers could contain constevalprohibited

# See also