Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

C++ destructor: object lifetime, coroutine frames, and PImpl

A destructor marks the end of an object's lifetime and cleans up its resources. Learn how an owner destroys a coroutine frame and why a PImpl destructor is defined out of line.

Version: ISO C++23; implementation support may vary

Syntax

// Destructor declared in the class, then defaulted outside it:
class T {
public:
    ~T();
};
T::~T() = default;

// A different class with a custom destructor and deleted copy operations:
class Owner {
public:
    Owner() = default;
    ~Owner() noexcept { /* release the owned resource */ }
    Owner(const Owner&) = delete;
    Owner& operator=(const Owner&) = delete;
};

A destructor ~T() is a special member function with no parameters or return type. In C++23, a class template can declare several prospective destructors with different constraints; overload resolution selects one for a specialization. A class object's lifetime ends when its destructor call starts. A fully constructed local object with automatic storage duration is destroyed on scope exit, including during stack unwinding. After the destructor body, members and then bases are destroyed in reverse construction order.

In ~T(), the tilde is part of the destructor name; in ~bits, it denotes bitwise complement. An explicit p->~T() does not deallocate the object's own storage; don't use it on a local object with automatic storage duration that will be destroyed again on scope exit. A valid delete p for a non-null pointer combines destruction and deallocation. For deletion of a derived object through a public base pointer, use a virtual base destructor. Don't let exceptions escape a destructor: escaping a noexcept destructor or escaping during stack unwinding calls std::terminate.

A TaskInt- or GeneratorStr-style frame owner uses RAII: its destructor calls h.destroy() only if h refers to a still-live, suspended coroutine. std::coroutine_handle is not itself an owner; copying it doesn't create another frame. Putting = delete on the copy constructor and copy assignment operator forbids copying at compile time; it does not free memory. If you add moves, transfer the handle, clear the source, and release the destination's old frame on move assignment.

In PImpl, struct Impl; declares an incomplete nested type. A std::unique_ptr<Impl> member is allowed, but its default deleter requires Impl to be complete where the deleter is invoked. Declare ~Widget(); in the class, then write Widget::~Widget() = default; after defining Impl, usually in the .cpp file. = default asks the compiler to generate ordinary member destruction; the constructor's colon starts the member initializer list, which initializes impl_ rather than assigning to it.

A user-declared destructor, even with = default, suppresses implicit declaration of both move operations. std::unique_ptr is noncopyable, so Widget is noncopyable too. To make Widget movable, explicitly declare both move operations and define them with = default after Impl is complete: move assignment may destroy the object previously owned by the destination's impl_.

Examples

#include <coroutine>
#include <cstdio>
#include <exception>
#include <memory>
#include <utility>

class Task {
public:
    struct promise_type;
    using Handle = std::coroutine_handle<promise_type>;

    Task(const Task&) = delete;
    Task& operator=(const Task&) = delete;
    ~Task() noexcept { if (h_) h_.destroy(); }

private:
    explicit Task(Handle h) noexcept : h_(h) {}
    Handle h_;
};

struct Task::promise_type {
    Task get_return_object() noexcept { return Task{Handle::from_promise(*this)}; }
    std::suspend_never initial_suspend() noexcept { return {}; }
    std::suspend_always final_suspend() noexcept { return {}; }
    void return_void() noexcept {}
    void unhandled_exception() noexcept { std::terminate(); }
    ~promise_type() { std::puts("frame: promise destroyed"); }
};

Task finish() { co_return; }

class Widget {
    struct Impl;
    std::unique_ptr<Impl> impl_;

public:
    Widget();
    ~Widget();
    Widget(Widget&&) noexcept;
    Widget& operator=(Widget&&) noexcept;
};

struct Widget::Impl {
    ~Impl() { std::puts("widget: implementation destroyed"); }
};

Widget::Widget() : impl_(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;

int main() {
    {
        auto task = finish();
        std::puts("leaving task scope");
    }
    {
        Widget first;
        Widget second = std::move(first);
        std::puts("leaving widget scope");
    }
}

Result

leaving task scope
frame: promise destroyed
leaving widget scope
widget: implementation destroyed

The output is expected, not measured. `finish()` reaches `co_return` and stays suspended at its final suspend point until `Task` leaves scope. After the move, only `second` owns the `Impl`, so each destruction message appears once. The example requires <coroutine> support in C++23 mode.

Related lessons

  • C++ · Lesson 41 · Advanced · Version: 3
  • C++ · Lesson 42 · Advanced · Version: 3
  • C++ · Lesson 43 · Advanced · Version: 3
  • C++ · Lesson 57 · Advanced · Version: 3

Sources