skip to content

In C++, how do you make a class non-copyable or move-only with = delete, and why is deleting its move constructor usually a mistake?

level: middleimportance: must knowfreq 62%

answer

  1. delete the two copy members
  2. default the two moves
  3. deleted still joins overload resolution
  4. omit, never delete, the moves

basics

~20 s

Declare the copy constructor and copy assignment = delete, and the moves = default if it should still move. Never delete the moves to mean no move: a deleted function still wins overload resolution, so moving an rvalue fails to compile.

solid answer

~50 s

`Image(const Image&) = delete;` and `Image& operator=(const Image&) = delete;` make copying ill-formed with a clear error, `call to deleted constructor of 'Image'`. Declaring them suppresses the implicit moves, so a movable type then adds `Image(Image&&) noexcept = default;` and the matching assignment; marking moves `noexcept` lets `std::vector` move elements when it reallocates. A deleted function is a real declaration that takes part in overload resolution and makes the program ill-formed if chosen. That is why `Image(Image&&) = delete;` backfires: an rvalue such as `return img;` or `static_cast<Image&&>(a)` picks the deleted move constructor over the copy constructor and fails, and `std::vector<Image>` rejects the type. To get copy-only behaviour, simply do not declare the moves: a user-declared copy constructor already stops them being declared, so rvalues fall back to copying. Often no deletions are needed at all, since a `std::unique_ptr` member makes the class move-only by itself.

code

cpp · 28 lines
cpp
#include <cstdio>
#include <utility>
#include <vector>

class Image {                                   // large: never copy one by accident
public:
    Image(int w, int h) : w_(w), h_(h), pixels_(w * h) {}
    Image(const Image&) = delete;               // non-copyable
    Image& operator=(const Image&) = delete;
    Image(Image&&) noexcept = default;          // but movable
    Image& operator=(Image&&) noexcept = default;
    ~Image() = default;
    int area() const { return w_ * h_; }
private:
    int w_, h_;
    std::vector<unsigned char> pixels_;
};

Image load() { Image img(64, 64); return img; }   // returning by value still works

int main() {
    std::vector<Image> frames;
    frames.push_back(load());
    frames.emplace_back(32, 32);
    Image first = std::move(frames.front());
    // Image copy = first;                       // error: call to deleted constructor
    std::printf("%zu frames, moved one of area %d\n", frames.size(), first.area());
}

go deeper

for a junior

Recall that = delete on the copy constructor and copy assignment makes a class non-copyable, and that std::unique_ptr members do this automatically.

for a middle

Explain why move-only classes must declare their moves = default, and why a deleted move constructor still gets selected for rvalues.

for a senior

Distinguish explicitly deleted moves from defaulted moves defined as deleted, keep moves noexcept for containers, and pick the right row of the copy and move table.

for a principal

Decide which domain types must be non-copyable, such as large buffers or handles, and prefer member-driven move-only semantics over hand-written deletions.

## Deleted functions Writing `= delete` instead of a body gives a function a **deleted definition**. The function is declared, so it takes part in name lookup and overload resolution, but the standard makes any program that uses it, other than to declare it, ill-formed. Before C++11 the idiom was to declare the copy operations `private` and leave them undefined; `= delete` replaces that with an error at the call site that names the problem. ## Non-copyable and move-only | Goal | Declarations | |---|---| | Copyable and movable | none (rule of zero) | | Move-only | copy operations `= delete`, move operations `= default` | | Non-copyable and non-movable | copy operations `= delete`, moves left undeclared | | Copy-only | user-declared copy operations, moves left undeclared | For move-only, the explicit `= default` moves are required, not decoration: once the class declares a copy constructor or copy assignment, even a deleted one, the compiler no longer declares the move constructor or move assignment. The code example builds a move-only `Image` that is cheap to move but too large to copy by accident. It can be returned by value, stored in `std::vector` and moved out, and an attempted copy fails with: ```plaintext mo3.cpp:26:11: error: call to deleted constructor of 'Image' ``` The `noexcept` on the defaulted moves matters: `std::vector` uses a move constructor during reallocation only when it cannot throw, or when the type cannot be copied at all. How that choice is made is covered with move semantics; here it is enough to keep moves `noexcept`. ## Why deleting the moves backfires A common mistake is to write `Image(Image&&) = delete;` to mean "do not move, copy instead". Because a deleted function still participates in overload resolution, an rvalue argument finds the move constructor the best match, selects it, and the program is ill-formed. With copy operations defaulted and moves deleted, Apple clang 21 rejects all three of these lines: ```plaintext delmove.cpp:10:34: error: call to deleted constructor of 'Image' delmove.cpp:13:11: error: call to deleted constructor of 'Image' error: static assertion failed due to requirement '__is_cpp17_move_insertable_v<std::allocator<Image>>' ``` The first is `return img;` inside a factory function, the second an explicit cast to `Image&&`, the third libc++ rejecting `std::vector<Image>::push_back`. To get copy-only behaviour, **do not declare** the moves. An undeclared move constructor is not a candidate, so an rvalue binds to `const Image&` and copies. There is one asymmetry worth knowing. The standard says a **defaulted** move special member that is defined as deleted, for example because a member cannot be moved, is excluded from the set of candidates. So `Image(Image&&) = default;` on a class with a non-movable member quietly falls back to copying, while an explicit `= delete` written by the programmer does not. ## =default and user-declared `= default` asks for the compiler's definition. If it appears on the first declaration, the function is user-declared but not **user-provided**, so it can still be trivial and it keeps the class's other properties where the rules depend on user-provided functions. It is still **user-declared**, though, and user-declared is what suppresses other special members: `~Image() = default;` stops the implicit moves exactly as `~Image() {}` does. ## Making a type move-only without deleting anything The simplest move-only class declares nothing: - A `std::unique_ptr<unsigned char[]>` member has deleted copy operations, so `Image`'s implicit copies are defined as deleted. - Its move operations exist and are `noexcept`, so `Image`'s implicit moves are generated. - The error message then says the copy constructor is implicitly deleted because the field has a deleted copy constructor, which points straight at the cause. Explicit deletions are still useful when the members are copyable but copying is wrong for the domain, as with the large frame buffer in the code example. ## Checklist for a move-only type - Delete both copy operations, or rely on a member whose copies are deleted. - Declare both move operations, `= default` where the members can move themselves, and mark them `noexcept`. - Declare the destructor only if you need one, and if you do, remember it suppresses the implicit moves. - Return by value and store in containers freely; both work with moves alone. - Test that a copy fails to compile, for example with `static_assert(!std::is_copy_constructible_v<Image>);`. ## Beyond special members `= delete` works on any function. Deleting an overload, such as `void scale(int) = delete;` next to `void scale(double);`, blocks a conversion at compile time; how that interacts with overload ranking belongs to the material on overloading.

  • In C++, a class declares Image(Image&&) = default; but has a member that cannot be moved. What happens to std::move(image)?
    The defaulted move constructor is defined as deleted, and the standard excludes a defaulted move special member defined as deleted from overload resolution. So the call falls back to the copy constructor if one is usable, and copies. If the copy constructor is deleted too, the program is ill-formed.
  • Why did C++ code before C++11 make copy operations private and leave them undefined?
    There was no `= delete`. Private declarations stopped outside code at compile time, and leaving them undefined turned accidental use by members or friends into a link error. `= delete` replaces both with one compile-time error at the call site, and the function can stay public so the diagnostic says deleted rather than inaccessible.

  • Declaring the move constructor = delete makes the class fall back to copying.
  • A deleted function is ignored by overload resolution.
  • Deleting the copy constructor keeps the implicit move constructor.
  • = default on a destructor keeps the implicit move operations.
  • A move-only type cannot be returned from a function by value.