Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Deleted function and constructor definitions: `= delete`

`= delete` forbids use of a specific function or constructor without removing it from the overload set. It does not destroy an object or release memory.

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

Syntax

struct IdGen {
    IdGen() = delete;
    explicit IdGen(int seed);
    explicit IdGen(double seed) = delete;
};

void f(double) = delete;

IdGen() = delete; explicitly defines the default constructor as deleted. Write = delete on the function's first declaration in place of a braced body. The same syntax works for ordinary functions and is part of C++23. The declaration itself does nothing at runtime.

A deleted function still participates in overload resolution. If it is selected, the program is ill-formed and the compiler must diagnose it; there is no fallback to another overload. IdGen{} selects the deleted default constructor. IdGen{42.5} selects the deleted double overload, while IdGen{42} works through the int constructor.

Do not confuse = delete with the expressions delete p and delete[] p. In typical valid use at runtime, they destroy an object created by new or the elements of an array created by new[], respectively, and call the corresponding deallocation function (operator delete or operator delete[]). That is an object-lifetime topic: cross-reference the object-model entry rather than duplicating the explanation of = delete there.

Examples

#include <iostream>

struct IdGen {
    IdGen() = delete;
    explicit IdGen(int seed) : next_id(seed) {}
    explicit IdGen(double) = delete;

    int next() { return next_id++; }

private:
    int next_id;
};

int main() {
    // IdGen no_seed{};
    // IdGen fractional{42.5};

    IdGen ids{42};
    std::cout << ids.next() << '\n';
    std::cout << ids.next() << '\n';
}

Result

42
43

The unchanged program prints `42` and `43` on separate lines. Uncomment each declaration separately and recompile to see the error for using a deleted constructor.

Related lessons

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

Sources