skip to content

Which C++ standard library types promise a specific state after being moved from, and which promise only a valid but unspecified one?

level: middleimportance: should knowfreq 45%

answer

  1. unless otherwise specified
  2. owners that become empty
  3. optional keeps its engagement
  4. containers and function stay open

basics

~10 s

unique_ptr, shared_ptr and weak_ptr become null, std::thread and unique_lock own nothing, and std::future becomes invalid. std::optional keeps has_value() unchanged. std::string, std::vector and std::function promise only a valid but unspecified state.

solid answer

~40 s

The default rule is *valid but unspecified*, and some types override it in their move constructor's postconditions. `std::unique_ptr` guarantees `u.get() == nullptr`; `std::shared_ptr` and `std::weak_ptr` leave the source empty; `std::thread` guarantees `x.get_id() == std::thread::id()`; `std::unique_lock` leaves the source with no mutex and not owning; a moved-from `std::future` has `valid() == false`. `std::optional` is the surprise: `rhs.has_value()` is unchanged, so a moved-from engaged optional still holds a moved-from value. Containers only promise that the target equals the source's old value, so a moved-from `std::vector` or `std::string` is unspecified, even though major implementations leave them empty. A moved-from `std::function` is also unspecified and may still have a target.

code

cpp · 25 lines
cpp
#include <cstdio>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::string name = "level_03_forest_terrain_heightmap";
    std::string taken = std::move(name);
    name = "level_04";                 // assigning a new value is always fine
    std::printf("name=%s\n", name.c_str());

    std::unique_ptr<int> owner = std::make_unique<int>(7);
    auto other = std::move(owner);
    std::printf("unique_ptr null: %d\n", owner == nullptr);       // guaranteed

    std::optional<std::string> slot = std::string(40, 'x');
    auto moved = std::move(slot);
    std::printf("optional has_value: %d, size=%zu\n", slot.has_value(), slot->size());

    std::vector<int> v{1, 2, 3};
    auto w = std::move(v);
    std::printf("vector size=%zu\n", v.size());    // unspecified by the standard
}

go deeper

for a junior

Remember that a moved-from std::unique_ptr is guaranteed null, while std::string and std::vector are only valid with an unknown value.

for a middle

List the types with specified moved-from states, and explain why std::optional stays engaged after its value is moved out.

for a senior

Catch review bugs that test a moved-from optional or function to decide whether work was consumed, and replace them with explicit reset() or assignment.

for a principal

Document moved-from postconditions for your own resource types the way the standard does, so callers know what they may test.

## The default and the exceptions The library introduction sets the default: objects of standard library types that have been moved from are placed in a **valid but unspecified state**, *unless otherwise specified*. "Otherwise specified" means a postcondition written on that type's move constructor or move assignment. Reading those postconditions is the only way to know which moved-from objects you may test and trust. ## Types with a specified moved-from state | Type | Postcondition on the source | What you can rely on | |---|---|---| | `std::unique_ptr<T>` | `u.get() == nullptr` | `if (!p)` is true after the move | | `std::shared_ptr<T>` | `r` is empty and `r.get() == nullptr` | it holds no ownership and no pointer | | `std::weak_ptr<T>` | `r` is empty, stores a null pointer, `r.use_count() == 0` | `expired()` is true | | `std::thread` | `x.get_id() == id()` | `joinable()` is false, so destroying it does not call `std::terminate` | | `std::unique_lock<M>` | no mutex, `owns_lock()` false | its destructor unlocks nothing | | `std::future<R>` | `valid() == false` | calling `get()` on it is undefined behaviour | | `std::optional<T>` | `has_value()` unchanged | an engaged source **stays engaged** with a moved-from `T` inside | The `std::optional` row is the one that catches people. Moving out of an engaged optional moves the contained value, but the optional itself stays engaged; `if (slot)` is still true, and `*slot` is a moved-from `T`. To empty it, call `slot.reset()` or assign `std::nullopt`. ## Types that promise only "valid but unspecified" - **Containers** (`std::vector`, `std::deque`, `std::map` and the rest): the container requirements only say that after `X u(rv)` the new object equals the value `rv` had; nothing is said about `rv`, so the general rule applies. - **`std::string`**: its move constructor states that the source is left in a valid but unspecified state. - **`std::function`**: if the source had a target, it is left "in a valid state with an unspecified value", so it may or may not still be callable. In practice libc++ leaves a moved-from `std::vector` and `std::string` empty, and the libstdc++ string move constructor sets the source's length to 0. Those are implementation choices that portable code must not depend on. ## Practical consequences 1. Testing `if (ptr)` after moving a `std::unique_ptr` is well-defined and is a common idiom for "did ownership go away?". 2. Testing `if (opt)` after moving out of a `std::optional` is a bug if you meant "was it consumed?"; the answer is still yes, it holds a value. 3. Re-using a moved-from `std::vector` or `std::string` needs a `clear()` or an assignment first. 4. Checking a moved-from `std::function` for emptiness with `if (cb)` tells you nothing reliable about whether the move happened; reset it with `cb = nullptr`. ## Why the differences exist For ownership types such as `std::unique_ptr` and `std::thread`, the moved-from state *is* the meaning of the move: ownership left the object, so the standard pins it down. `std::optional` deliberately mirrors its contained type: it moves the value and leaves engagement to the caller. Containers and `std::function` keep the general rule, which leaves implementations room in how they move; a `std::function` that stores a small callable inside itself, for example, may move that callable rather than hand over a pointer. ## A review checklist for moved-from objects When reviewing code that moves an object and then touches it again, ask: - Does the next use rely on a value? If the type is a container, `std::string` or `std::function`, the value is unspecified, so the code needs a `clear()`, a reset or an assignment first. - Does the next use test emptiness to mean "the move happened"? That is reliable for `std::unique_ptr`, `std::shared_ptr` and `std::thread`, and wrong for `std::optional`, whose engagement does not change. - Is the object an element of a container that will later be read in a loop? Moved-from elements left in a `std::vector` are still elements; erase them or give them new values. These questions turn the table above into habits that catch the bugs before a sanitizer or a crash does. ## How to check a type you have not met Look up its move constructor in the standard or on a reference site and read the **Postconditions** (written "Ensures" in the draft). If none mentions the source, assume only valid but unspecified.

  • How do you make a moved-from std::optional report that it is empty?
    Empty it explicitly: `slot.reset()` or `slot = std::nullopt` after the move. If the goal is to take the value out and leave the optional disengaged in one step, write `auto v = std::move(*slot); slot.reset();`. The optional's move constructor and move assignment leave `has_value()` exactly as it was.
  • Is it safe to call a moved-from std::function?
    Only after checking it. The standard leaves a moved-from `std::function` with a target in a valid state with an unspecified value: it might be empty, so calling it throws `std::bad_function_call`, or it might still hold a callable. Assign `nullptr` or a new callable before relying on it.

  • A moved-from std::optional is always disengaged, so if (opt) becomes false.
  • Every moved-from standard object is guaranteed to be empty.
  • A moved-from std::unique_ptr has an unspecified value that you must not test.
  • The standard guarantees a moved-from std::vector has size zero.
  • A moved-from std::function is guaranteed empty, so calling it always throws.