Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

`default` in C++: a defaulted destructor vs. a `switch` label

`~T() = default;` asks the compiler to define a destructor by the language rules. `default:` marks where a `switch` starts executing when no `case` matches.

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

Syntax

struct T {
    ~T() = default;
};

// Inside a function:
switch (value) {
    case 1:
        break;
    default:
        break;
}

The key distinction is definition versus control flow: ~T() = default; explicitly requests the compiler-generated destructor; it does not call it. When a local object is destroyed on leaving its block, its class-type non-static data members and base subobjects are destroyed as well.

A destructor defaulted on its first declaration can be trivial if it meets the other requirements. A handwritten empty body, ~T() {}, is not trivial, even though it still causes subobjects to be destroyed. The compiler can define a defaulted destructor as deleted, for example if a required member destructor is inaccessible.

In a switch, default: is optional and there can be at most one per switch. Control jumps directly to it when no case matches. If there is no default: either, the switch body is skipped. The label itself does not stop execution: control can fall through to it from an earlier branch if nothing, such as break, intervenes.

Examples

#include <iostream>

struct Trace {
    ~Trace() { std::cout << "member destroyed\n"; }
};

struct Item {
    Trace trace;
    ~Item() = default;
};

int main() {
    {
        Item item{};
        const int value = 7;
        switch (value) {
            case 1:
                std::cout << "case 1\n";
                break;
            default:
                std::cout << "default branch\n";
                break;
        }
    }
    std::cout << "after block\n";
}

Result

default branch
member destroyed
after block

`7` does not match `case 1`, so `default branch` is printed first. On leaving the block, the `Item` destructor destroys `trace`, whose destructor prints `member destroyed`. Only then does the program print `after block`.

Related lessons

  • C++ · Lesson 36 · Intermediate · Version: 2

Sources