Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Explicitly deleted function or constructor definition: `= delete`

`= delete` prohibits use of a particular function or constructor. The declaration still participates in overload resolution and does not deallocate memory.

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

Syntax

IdGen() = delete;                  // inside the class definition of IdGen
void set_id(double) = delete;      // at namespace scope

Inside IdGen, IdGen() = delete; declares the default constructor and is also its explicitly deleted definition. A constructor has no return type, and = delete; replaces the brace-enclosed body; it is not an assignment. This form must appear on the function's first declaration. It also works for an ordinary namespace-scope function, such as void set_id(double) = delete;.

A deleted overload still participates in overload resolution. An ordinary call that selects it is ill-formed and requires a diagnostic; overload resolution does not fall back to the next-best overload. If substituting template arguments into a dependent requirement makes it invalid because it would use a deleted function, the requires expression can evaluate to false without making the program ill-formed. In the example, IdGen{42} selects the int constructor, IdGen{} selects the deleted default constructor, and IdGen{3.5} selects the deleted double constructor rather than converting the argument to int.

This is not the delete p or delete[] p expression. Those expressions operate on a pointer and are used to destroy objects created by the corresponding new or new[] and release their storage through deallocation functions such as operator delete or operator delete[]. A = delete; definition does not end an object's lifetime, release storage, or throw an exception.

The = delete; form has existed since C++11 and is part of C++23. The form with a reason, = delete("reason");, is not part of C++23; support for that later syntax depends on the implementation.

Examples

#include <iostream>

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

    int id;
};

int main() {
    IdGen valid{42};
    // IdGen missing{};
    // IdGen fractional{3.5};
    std::cout << valid.id << '\n';
}

Result

42

As written, the program prints `42`. Uncomment each of the two lines separately to see a compilation error from selecting the corresponding deleted constructor. Diagnostic wording depends on the compiler.

Related lessons

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

Sources