§The Annotated C++ StandardC++ 标准注疏 中文
11.4.7

Destructors

How destructors are declared and selected from several prospective destructors; when they are deleted or trivial and why they are noexcept by default; the destruction order of members and bases, when destructors are invoked implicitly, virtual destructors and operator delete, and the rules for explicit destructor calls.

Key points

  • Every class has a destructor; if the user doesn't declare one, the compiler implicitly declares it. Since C++20 a class can have several constrained prospective destructors, and overload resolution picks one of them at the end of the class definition.
  • A destructor written without noexcept has the same exception specification as the implicitly-declared one, which is usually noexcept; throwing out of it calls std::terminate.
  • A destructor runs its body first, then destroys members and bases in the reverse order of the completion of their construction.
  • When a derived object is deleted through a base class pointer, the base class must have a virtual destructor; otherwise the behavior is undefined.
  • Invoking a destructor for an object whose lifetime has already ended is undefined behavior. The commonest case is explicitly destroying a local variable, which is then destroyed again at the end of its scope.

The destructor is the end point of an object's lifetime. For a class type, the lifetime of an object ends as soon as its destructor call starts ([basic.life]/2). What RAII guarantees at the language level, that resources are always released when leaving a scope and in a definite order, comes from this subclause.

Declaring destructors (¶1–¶3)#

C++✓ well-formed
struct S {
    ~S();
};
S::~S() { }

struct T {
    virtual ~T() = default;
};
C++✗ ill-formed
struct A {
    ~A(int);      // error: can't have parameters
};
struct B {
    void ~B();    // error: can't have a return type
};
struct C {
    static ~C();  // error: can't be static
};

¶1 A declaration whose name starts with ~ declares a prospective destructor (prospective destructor). Why "prospective" is explained in the next section. Its form is similar to a constructor's ([class.ctor.general]/1):

  • ¶1.1 in a member declaration inside a class definition, it is written ~class-name, where class-name is the injected-class-name of the immediately-enclosing class;
  • ¶1.2 otherwise (an out-of-class definition, a friend declaration), it is written nested-name-specifier ~class-name, as in S::~S.

A prospective destructor can't have parameters (() or (void)) and has no return type. The only specifiers allowed are friend, inline, virtual and constexpr. As with constructors, in a class template write ~X();, not ~X<T>();.

¶2 If a class has no user-declared prospective destructor and is not an anonymous union, the compiler implicitly declares a defaulted prospective destructor (its definition is generated by the compiler), which is an inline public member of the class. ¶3 Its form is ~X().

Other special member functions stop being implicitly declared when the user declares certain other members; the destructor has no such suppression. Every class other than an anonymous union has a destructor.

Selecting the destructor from the prospective destructors (¶4)#

C++select-dtor.cpp✓ well-formedgodbolt ↗
#include <type_traits>
#include <string>

template<class T>
struct Box {
    ~Box() requires std::is_trivially_destructible_v<T>
        = default;           // #1
    ~Box() { t.~T(); }       // #2
    union { T t; };
    Box() : t() { }
};

static_assert( std::is_trivially_destructible_v<Box<int>>);
static_assert(!std::is_trivially_destructible_v<Box<std::string>>);

int main() { Box<std::string> b; (void)b; }

¶4 At the end of the class definition (except for anonymous unions), the compiler performs overload resolution with an empty argument list among all the prospective destructors declared in the class; the one selected is the class's destructor, also called the selected destructor. If overload resolution fails, the program is ill-formed.

A destructor has no parameters, so multiple prospective destructors can only be told apart by their constraints (requires-clauses). In the example above, when T is trivially destructible, the constraint of #1 is satisfied and #1 is more constrained than the unconstrained #2, so #1 is selected and Box<int>'s destructor is trivial; otherwise only #2 is viable. This is part of C++20's conditionally trivial special member functions (P0848R3); wrapper types such as std::optional rely on it to stay trivial themselves when T is trivial.

¶4 ends by saying that selecting the destructor does not odr-use it, so the selected destructor may be deleted. Also, per [dcl.fct.def.default]/5, a defaulted prospective destructor that isn't selected is defined as deleted; it would never be called anyway.

const during destruction, and prohibitions (¶5, ¶20)#

¶5 The address of a destructor can't be taken, and a return in a destructor body can't have a value.

A destructor can be invoked for a const, volatile or const volatile object. const and volatile semantics are not applied to an object under destruction; they stop being in effect when the destructor for the most derived object starts. This mirrors construction ([class.ctor.general]/4): the destructor of a const object can modify members, for example to null out a pointer.

¶20 A destructor can't be a coroutine.

noexcept by default (¶6)#

C++dtor-noexcept.cpp✓ well-formedgodbolt ↗
#include <type_traits>

struct T { ~T() { } };
struct U { ~U() noexcept(false) { } };
struct V { U u; ~V() { } };

static_assert( std::is_nothrow_destructible_v<T>);
static_assert(!std::is_nothrow_destructible_v<U>);
static_assert(!std::is_nothrow_destructible_v<V>);
int main() { }

¶6 Note 2 points out that a destructor declaration without an exception specification has the same exception specification as an implicitly-declared destructor would ([except.spec]). So as long as the destructors of the bases and members don't throw, a user-written destructor is noexcept too, even if its body contains a throw. Only because V's member U may throw on destruction is V's destructor noexcept(false) as well.

This was a C++11 change; in C++98 a destructor without an exception specification could throw anything. The reason for the change is that destructors are called during stack unwinding, where throwing another exception can only lead to std::terminate; the standard library also requires element types' destructors not to throw. When a failure during destruction needs to be reported, provide a separate member such as close() and let the caller handle it.

When it is defined as deleted (¶7)#

¶7 A defaulted destructor for class X is defined as deleted (as if = delete) if:

  • ¶7.1 X is not a union, and some non-variant potentially constructed subobject (potentially constructed subobjects, the direct bases, non-static data members and virtual bases) has class type M (or multidimensional array thereof) whose destructor is deleted or inaccessible from here;
  • ¶7.2 X is a union and either:
    • ¶7.2.1 overload resolution to select a constructor to default-initialize X fails, or the selected constructor is deleted or non-trivial; or
    • ¶7.2.2 some variant member (variant member, a member of a union) of class type M has a default member initializer and M has a non-trivial destructor;
  • ¶7.3 the destructor is virtual and lookup of the non-array operator delete is ambiguous, or finds a function that is deleted or inaccessible (see ¶15 below).

Destroying unions C++26#

A union's destructor doesn't know which member is active, so it destroys no members. ¶7.2 answers the question: when is doing nothing safe?

  • When the union's default constructor is trivial, a default-constructed union has no active member, and destroying nothing is right;
  • When the default constructor is non-trivial (a variant member has a default member initializer, or the user provided a constructor), it may have started the lifetime of some member, which then needs destroying. So the defaulted destructor is deleted, forcing the user to write one.
C++union-dtor.cpp
#include <string>

union U1 { std::string s; };         // C++26: trivial destructor
union U2 { std::string s = "x"; };   // destructor deleted (¶7.2.2)
union U3 {                           // takes care of it itself
    std::string s;
    U3() : s() { }
    ~U3() { s.~basic_string(); }
};
int main() { U3 u; (void)u; }

The C++23 rule was: as soon as some variant member has a non-trivial destructor, the union's defaulted destructor is deleted, so U1 had to write ~U1() { } by hand. C++26 trivial unions (P3074R7) changed it to the rule above; the other half of the change is on the default constructor side ([class.default.ctor]/2). Clang 23 doesn't implement this change yet, so the example carries no verdict.

Trivial destructors (¶8)#

¶8 A destructor can be trivial only if it is not user-provided (user-provided, user-declared and not defaulted or deleted on its first declaration), and in addition:

  • ¶8.1 it is not virtual;
  • ¶8.2 all direct base classes have trivial destructors;
  • ¶8.3 the class is a union, or every non-variant non-static data member of class type (or array thereof) has a trivial destructor.

A trivial destructor does nothing. It is a necessary condition for trivially copyable types ([class.prop]/1) and implicit-lifetime types ([class.prop]/8).

By ¶8.1, a virtual destructor is not trivial even if written = default, so polymorphic types are not trivially copyable.

Implicit definition (¶9–¶10)#

¶9 A defaulted destructor is a constexpr destructor (since C++20, destructors can be constexpr). ¶10 Before a defaulted destructor is implicitly defined, all the non-user-provided destructors of its bases and members are implicitly defined first.

¶12 Note 3 points out that operations such as calling virtual functions during destruction have special semantics; see [class.cdtor].

Order of destruction (¶13)#

C++dtor-order.cpp✓ well-formedgodbolt ↗
#include <cstdio>

struct M {
    const char* n;
    ~M() { std::printf("~M(%s) ", n); }
};
struct B1 { ~B1() { std::printf("~B1 "); } };
struct B2 { ~B2() { std::printf("~B2 "); } };

struct X : B1, B2 {
    M a{"a"}, b{"b"};
    ~X() { std::printf("~X-body "); }
};

int main() {
    { X x; }   // ~X-body ~M(b) ~M(a) ~B2 ~B1
    std::printf("\n");
}

¶13 After executing its body and destroying the automatic objects allocated within the body, a destructor calls, in turn:

  1. the destructors of the direct non-variant non-static data members (except anonymous unions);
  2. the destructors of the non-virtual direct base classes;
  3. if X is the most derived class, the destructors of the virtual base classes.

All these calls are made as if with qualified names, without virtual dispatch. Bases and members are destroyed in the reverse order of the completion of their construction, and array elements are also destroyed in reverse order of construction ([class.init]). So a return in a destructor doesn't go straight back to the caller; the members and bases still have to be destroyed afterwards (note 4).

The reverse order is what makes RAII correct: a member constructed later may depend on one constructed earlier, for example by holding a reference to it, so it has to be destroyed first.

When destructors are invoked implicitly (¶14)#

¶14 A destructor is invoked implicitly:

  • ¶14.1 for a constructed object with static storage duration, at program termination ([basic.start.term]);
  • ¶14.2 for a constructed object with thread storage duration, at thread exit;
  • ¶14.3 for a constructed object with automatic storage duration, when the block in which it was created exits ([stmt.dcl]);
  • ¶14.4 for a constructed temporary object, when its lifetime ends ([class.temporary]).

For an object created by a new-expression, the destructor can be invoked through a delete-expression. Destructors can also be invoked explicitly (¶16).

C++dtor-access.cpp✗ ill-formed
struct P { private: ~P(); public: P(); };

P* mk() { return new P; }       // OK
void f(P* p) { delete p; }      // error: the destructor is private
void g() { P local; }           // error: it must be called when the block exits
P* arr() { return new P[2]; }   // error: array new potentially invokes the destructor

¶14 also defines potentially invoked (potentially invoked (destructor)): a destructor is potentially invoked if it is invoked, or may be invoked in the situations specified in [expr.new], [stmt.return], [dcl.init.aggr], [class.base.init] and [except.throw]. The typical case is an exception thrown partway through construction, where the parts already constructed must be destroyed. If a potentially invoked destructor is deleted or not accessible from the context of the invocation, the program is ill-formed.

In the example above, if constructing the second element of new P[2] throws, the first one must be destroyed, so it potentially invokes the destructor; new P has no such rollback and doesn't. For an implicit invocation, access is checked in the context where the object was constructed; for an invocation via delete, the context is that delete-expression. So a private destructor can be used to restrict objects to being created on the heap, together with a destroy() member or a friend deleter.

Virtual destructors (¶11, ¶15)#

When you need one (¶11)#

C++non-virtual-dtor.cpp☠ undefined behavior
#include <string>

struct Base { };   // destructor is not virtual
struct Derived : Base { std::string s = "leak?"; };

int main() {
    Base* p = new Derived;
    delete p;      // UB: Base has no virtual destructor
}

When an object will be deleted through a base class pointer, the base class needs a virtual destructor. If the static type of the object in a delete expression differs from its dynamic type and the static type has no virtual destructor, the behavior is undefined ([expr.delete]).

A common claim is that this merely leaks the members of Derived. That's not right. The standard says it is undefined behavior; in practice memory may also be freed with the wrong size, and with multiple inheritance the wrong address may even be passed to operator delete.

¶11 A prospective destructor can be declared virtual, and can be declared pure virtual. If a class's destructor is virtual and the program creates objects of that class or a derived class, the destructor must be defined, even if it is pure virtual:

C++pure-virtual-dtor.cpp✓ well-formedgodbolt ↗
struct Shape {
    virtual ~Shape() = 0;    // Shape is an abstract class
};
Shape::~Shape() = default;   // still must be defined

struct Circle : Shape { };

int main() {
    Shape* p = new Circle;
    delete p;   // ~Circle, then ~Shape
}

After a derived class's destructor finishes, it always calls the base class destructor by qualified name (¶13), so the base destructor must exist. The only use of a pure virtual destructor is to make a class abstract when it has no other pure virtual functions.

Looking up operator delete when a virtual destructor is defined (¶15)#

C++✓ well-formed
struct A {
    void operator delete(void*)
        = delete;
    virtual ~A() = default;
    // defaulted: defined as deleted (¶7.3)
};
C++✗ ill-formed
struct B {
    void operator delete(void*)
        = delete;
    virtual ~B() { }
    // error: user-provided, and the
    // operator delete found is deleted (¶15)
};

¶15 At the point of definition of a virtual destructor (including an implicit definition), the compiler must already determine the non-array deallocation function, as if for the expression delete this appearing in a non-virtual destructor of the class ([expr.delete]). If the lookup fails or finds a deleted function, the program is ill-formed. Note 6 says this ensures that the operator delete corresponding to the dynamic type of an object is available to the delete expression ([class.free]).

The class on the left defaults its destructor, and ¶7.3 makes it defined as deleted; Clang 23 only gives a -Wdefaulted-function-deleted warning. Such a type can't be destroyed, so no automatic objects of it can be created. The destructor on the right is user-provided, and ¶15 makes the program ill-formed outright, even if the program never deletes a B.

Itanium ABI: D0, D1, D2

The Itanium C++ ABI generates up to three variants of each destructor: D2 (base object destructor) destroys the object as a base class subobject and doesn't destroy virtual bases; D1 (complete object destructor) destroys a complete object, including virtual bases; D0 (deleting destructor) calls D1 and then the class's selected operator delete. Only virtual destructors have a D0, and it and D1 both go in the vtable.

When the static type has a virtual destructor, delete p; compiles to a call of D0 through the vtable, so operator delete is determined by the dynamic type. [class.free] says the effect is as if it were a virtual function, and this is how it is implemented; ¶15 requires operator delete to be found when the virtual destructor is defined because that is where D0 is generated. Destruction of automatic and static objects calls D1, and a derived class's destructor calls the base's D2. MSVC does it differently, with a scalar deleting destructor that takes a hidden flag parameter.

Explicit destructor calls (¶16–¶19)#

Syntax and virtual dispatch (¶16)#

C++explicit-dtor-call.cpp✓ well-formedgodbolt ↗
#include <new>
#include <cstdio>

struct B { virtual ~B() { std::puts("~B"); } };
struct D : B { ~D() { std::puts("~D"); } };

int main() {
    alignas(D) unsigned char buf[sizeof(D)];
    typedef B B_alias;

    B* p = ::new (buf) D;
    p->~B();            // virtual call: ~D ~B
    p = ::new (buf) D;
    p->~B_alias();      // same
    p = ::new (buf) D;
    p->B_alias::~B();   // qualified name: only ~B
}

¶16 An explicit destructor call is written ~ followed by a type name or decltype specifier that denotes the class type. An unqualified p->~B() uses virtual dispatch like any virtual function call; a qualified p->B_alias::~B() doesn't, and only calls B's destructor. After the last call, the lifetime of the object in buf has ended, but D's destructor never ran; that is valid, but usually a bug.

Calling a destructor follows the usual rules for member functions ([class.mfct]): if the object is neither of the destructor's class type nor of a type derived from it, the behavior is undefined, and that includes calling it through a null pointer. Note 7 points out that delete on a null pointer doesn't call a destructor at all.

Note 8 points out that an explicit destructor call must be written as a member access (p->~X(), x.~X()) or with a qualified name (X::~X() inside a member function). Writing ~X() alone in a member function applies the unary ~ operator to the temporary X() ([expr.unary.op]).

¶17 Note 9 says explicit destructor calls are rarely needed; the typical use is together with placement new to manage objects at specific addresses, as in memory pools and the implementations of std::optional and std::vector. Since C++17 you can use std::destroy_at(p), which also works for arrays and doesn't require spelling the type name.

Don't destroy twice (¶18)#

C++double-destroy.cpp☠ undefined behavior
#include <string>

int main() {
    std::string s = "a fairly long string that lives on the heap";
    s.~basic_string();   // lifetime ends
}                        // UB: s is destroyed again when the block exits

¶18 Once a destructor is invoked for an object, its lifetime has ended. Invoking a destructor for an object whose lifetime has ended is undefined behavior ([basic.life]).

Example 3 is the situation above: an automatic object is destroyed explicitly, then the block exits normally and destroys it again implicitly. In our tests AddressSanitizer reports a double free. The fix is to construct a new object in the same place with placement new before the scope ends; see [basic.life].

Pseudo-destructors for scalar types (¶19)#

C++pseudo-dtor.cpp✓ well-formedgodbolt ↗
#include <new>

template<class T>
void destroy(T* p) { p->~T(); }   // a pseudo-destructor call when T = int

int main() {
    int i = 1;
    typedef int I;
    I* p = &i;
    p->I::~I();          // ends the lifetime of i
    ::new (&i) int(2);   // starts it again
    destroy(&i);
    ::new (&i) int(3);
    return i - 3;
}

¶19 Note 10 says the notation for explicit destructor calls can be used with any scalar type name ([expr.prim.id.dtor]), so generic code doesn't need to distinguish types with and without destructors. Since C++20, such a pseudo-destructor call ends the object's lifetime ([basic.life]/2); before that it did nothing. This makes std::destroy_at behave the same for scalar and class types, and lets constant evaluation detect uses after destruction.

History#

History

  • C++98 already had destructors, virtual destructors and explicit destructor calls; pseudo-destructor calls did nothing.
  • Since C++11, destructors are noexcept by default; = default, = delete and the "defined as deleted" rules were introduced.
  • C++20 introduced prospective destructors and destructor selection (P0848R3), constexpr destructors and destroying operator delete ([class.free]); pseudo-destructor calls now end the lifetime; ~X<T>() is no longer allowed in class templates.
  • C++26 trivial unions (P3074R7) decide whether a union's defaulted destructor is deleted based on whether its default constructor is trivial.

Common misconceptions#

A polymorphic base class without a virtual destructor

For a class with virtual functions, the destructor should be either public and virtual, or protected and non-virtual so that deletion through a base pointer is forbidden. GCC's and Clang's -Wnon-virtual-dtor warns about classes that have virtual functions but no virtual destructor.

Thinking a = default virtual destructor is trivial

A virtual destructor is never trivial (¶8.1), so polymorphic types are not trivially copyable.

Questions#

Question 1

C++
template<class T> struct W {
    ~W() requires (sizeof(T) > 4);
    ~W() requires (sizeof(T) > 2);
};
W<int> a;     // (1)
W<double> b;  // (2)
Answer

(1) On mainstream implementations sizeof(int) == 4, so only the second constraint is satisfied and it is selected. The program is well-formed, but its definition is needed at link time.

(2) sizeof(double) == 8, so both constraints are satisfied. sizeof(T) > 4 and sizeof(T) > 2 are two different atomic constraints; partial ordering of constraints only compares whether atomic constraints are identical and does no numeric reasoning, so neither is more constrained than the other. Overload resolution is ambiguous and by ¶4 the program is ill-formed; Clang 23 reports an ambiguous destructor when instantiating W<double>.

Question 2

Why does ¶15 look up operator delete when the virtual destructor is defined, rather than waiting until a delete expression appears?

Answer

At delete p; only the static type of p is known, but which operator delete should be called is determined by the dynamic type ([class.free]). Only the dynamic type's own virtual destructor knows the dynamic type. In implementations, the deleting destructor D0 is generated where the virtual destructor is defined, and it calls the class's operator delete there. So the lookup has to happen at that point, even if the program never deletes an object of the class.

The authoritative text is eel.is/c++draft/class.dtor (working draft 2026-08-23, commit c7015b485c). These are study notes that explain rather than quote; ¶ numbers follow the draft. Translated from the Chinese original. Last updated 2026-10-19.