Skip to content

Transfer Move-Only Ownership

The Course
•
35 min study

The engine owns its rules through std::unique_ptr, and the engine itself must be able to change hands: a factory builds it, a test passes it to a helper, a container stores it. None of that may copy the rules, because two engines sharing one set of owned rules would destroy them twice. So the engine is move-only: it can be transferred, never duplicated. This lesson shows what a move really is, what is left behind, and how to build a move-only type without writing any special member functions yourself.

Predict and run

Predict before running C++
#include <iostream>
#include <memory>
#include <utility>

int main() {
    auto first = std::make_unique<int>(7);
    auto second = std::move(first);
    std::cout << (first == nullptr) << " " << *second << "\n";
    return 0;
}
Check your prediction
Text
1 7

second now owns the integer and first is empty. The standard promises that a moved-from unique_ptr is null, so testing it is well-defined. Dereferencing it is not: *first after the move dereferences a null pointer, which is undefined behavior. The first object still exists and will still be destroyed at the end of main; it just owns nothing, so its destructor does nothing.

std::move does not move

std::move(x) is a cast. It turns x into an rvalue expression, which says "you may steal from this". The actual transfer happens only if the receiving constructor or assignment has an overload for rvalues. If none matches, overload resolution falls back to copying, silently. The common way to fall into that is moving a const object, because a move constructor needs a non-const source it can modify:

Moving a const object copies it C++
#include <iostream>
#include <utility>

struct Counted {
    Counted() = default;
    Counted(const Counted&) { std::cout << "copy\n"; }
    Counted(Counted&&) noexcept { std::cout << "move\n"; }
};

int main() {
    Counted plain;
    const Counted fixed;
    Counted a = std::move(plain);
    Counted b = std::move(fixed);
    (void)a; (void)b;
    return 0;
}
Text
move
copy

std::move(fixed) produces a const Counted&&, which cannot bind to Counted&&, so the copy constructor runs. With a move-only type the same mistake is at least loud: std::move on a const std::unique_ptr<int> is fine on its own, but initializing a new unique_ptr from it fails to compile, because there is no copy constructor to fall back on.

What is left behind

After a move, the source still exists and will be destroyed. What state it is in depends on the type:

  • std::unique_ptr is guaranteed to be null.
  • Most standard library types, such as std::string and std::vector, are left in a valid but unspecified state. You may destroy them or assign a new value. Reading their contents tells you nothing reliable, so this course never prints a moved-from string.
  • Your own types promise whatever you design and document.

The safe habit is the same for all of them: after moving from an object, either let it die or assign it a fresh value before using it again. That is the rule the engine follows. A moved-from Engine is only destroyed or reassigned.

Move-only by composition

You rarely need to write move operations by hand. If a class holds a unique_ptr member, the compiler cannot generate a copy constructor for it, so copying is implicitly deleted, while the generated move constructor moves each member. That is the rule of zero again, now producing a move-only type. Static assertions state the result as a compile-time fact:

A member decides what the class can do C++
#include <iostream>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>

class Log {
public:
    explicit Log(std::string text) : text_(std::make_unique<std::string>(std::move(text))) {}
    bool empty() const { return text_ == nullptr; }
    const std::string& text() const { return *text_; }
private:
    std::unique_ptr<std::string> text_;
};

static_assert(!std::is_copy_constructible_v<Log>);
static_assert(std::is_move_constructible_v<Log>);
static_assert(std::is_nothrow_move_constructible_v<Log>);

int main() {
    Log first("created 2");
    Log second = std::move(first);
    std::cout << first.empty() << " " << second.empty() << " " << second.text() << "\n";
    return 0;
}
Text
1 0 created 2

Calling first.empty() after the move is legitimate here, unlike reading a moved-from string, because Log defines its moved-from state in terms of its unique_ptr member, which is guaranteed null. When you design a move-only type, decide that state on purpose and say which operations remain valid on it.

The engine's header spells out the same intent explicitly: it deletes the copy constructor and copy assignment and defaults the move operations. Writing them out documents the design for a reader, and the compile-time checks on Day 6 verify it.

Why moves should be noexcept

When a std::vector grows, it moves its elements into a new buffer. If a move could fail halfway through, the vector would be left with some elements in the old buffer and some in the new one. So with exceptions enabled, a vector moves elements only if their move constructor is noexcept, and copies them otherwise, which is slower. A move-only type has no copy, so the vector moves it anyway and gives up its promise to leave the old buffer intact if a move fails. This course compiles with exceptions disabled, and its standard library may move regardless, but the contract still matters for code built elsewhere. Moves that only transfer pointers cannot fail, so mark hand-written ones noexcept, and check generated ones with std::is_nothrow_move_constructible_v, as the Log example does.

Practice

Exercise

Your turn

Use the Log class above. Write a sink void archive(Log log) that prints archived TEXT. In main, put Log("created 2") and Log("adjusted 2") into a std::vector<Log>, move the first element into archive, then print whether each element is empty and the second element's text. Finally, reassign the first element with Log("renamed 2") and print its text. Expected:

Shell
archived created 2
empty: 1 0
second: adjusted 2
reused: renamed 2
Your workspace C++
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class Log {
public:
    explicit Log(std::string text) : text_(std::make_unique<std::string>(std::move(text))) {}
    bool empty() const { return text_ == nullptr; }
    const std::string& text() const { return *text_; }
private:
    std::unique_ptr<std::string> text_;
};

int main() {
    // Build the vector, archive the first log, then reuse its slot.
    return 0;
}
Hint 1: the idea

The vector owns its elements. Moving logs[0] transfers its contents to the parameter but leaves an empty Log in the vector.

Hint 2: a first step

A braced list such as std::vector<Log>{Log("a"), Log("b")} needs copies, so use push_back(Log("created 2")) or emplace_back("created 2") instead.

Show one solution
Run the solution C++
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class Log {
public:
    explicit Log(std::string text) : text_(std::make_unique<std::string>(std::move(text))) {}
    bool empty() const { return text_ == nullptr; }
    const std::string& text() const { return *text_; }
private:
    std::unique_ptr<std::string> text_;
};

void archive(Log log) { std::cout << "archived " << log.text() << "\n"; }

int main() {
    std::vector<Log> logs;
    logs.emplace_back("created 2");
    logs.emplace_back("adjusted 2");
    archive(std::move(logs[0]));
    std::cout << "empty: " << logs[0].empty() << " " << logs[1].empty() << "\n";
    std::cout << "second: " << logs[1].text() << "\n";
    logs[0] = Log("renamed 2");
    std::cout << "reused: " << logs[0].text() << "\n";
    return 0;
}
Text
archived created 2
empty: 1 0
second: adjusted 2
reused: renamed 2

The vector still has two elements after the move; one of them is an empty shell that the class defines as safe to test and safe to assign. Calling logs[0].text() before the reassignment would dereference a null pointer, which is why empty() exists. An std::initializer_list only exposes const elements, so a braced list of move-only values cannot be moved from, which is the trap Hint 2 avoids. Next you give the engine runtime-selected behavior with a virtual Rule interface.

Was this article helpful?

Your response is saved on this device.