skip to content

In C++, after std::string b = std::move(a); runs, what state is a left in, and what can you still do with it?

level: juniorimportance: must knowfreq 70%

answer

  1. the library's three-word phrase
  2. invariants still hold
  3. operations without preconditions
  4. assign or clear before reading

basics

~20 s

A moved-from std::string is in a valid but unspecified state: you may destroy it, assign to it, clear it or ask its size, but must not rely on its value, not even on it being empty.

solid answer

~40 s

The move constructor of `std::string` takes `a`'s characters, and the standard says only that a moved-from library object is left in a *valid but unspecified state*. Valid means its invariants hold and every operation behaves as specified for `std::string`; unspecified means you cannot know its value. So anything without a precondition is fine: destroy it, assign a new value, call `clear()`, `size()` or `empty()`. Anything with a precondition, such as `front()`, `back()` or `pop_back()`, needs a check first. In practice libc++ and libstdc++ leave the string empty, but that is their choice, not a promise, so code that appends to `a` again should `clear()` it first.

code

cpp · 20 lines
cpp
#include <cstdio>
#include <string>
#include <utility>
#include <vector>

int main() {
    const char* assets[] = {"forest.mesh", "forest.tex", "forest.nav", "cave.mesh"};
    std::vector<std::string> batches;
    std::string batch;
    for (const char* name : assets) {
        batch += name;
        batch += ';';
        if (batch.size() > 20) {
            batches.push_back(std::move(batch));  // batch: valid but unspecified
            batch.clear();                        // no precondition, so always allowed
        }
    }
    if (!batch.empty()) batches.push_back(std::move(batch));
    for (const auto& b : batches) std::printf("%s\n", b.c_str());
}

go deeper

for a junior

Say the phrase valid but unspecified and give examples on both sides: assigning, clearing and destroying are fine, relying on the old text or calling front() unchecked is not.

for a middle

Explain the definition: invariants hold and operations behave as specified, but the value is unknown, so only operations without preconditions are safe without a check.

for a senior

Spot code that appends to a moved-from accumulator and depends on it being empty; fix it with clear() and explain why it passes tests on libc++ and libstdc++ anyway.

for a principal

Frame a review rule: after std::move, the next touch of that variable is a reassignment, a clear() or the end of its scope, which keeps code portable across standard libraries.

## What the move did to `a` `std::move(a)` changes nothing by itself: it only lets `a` bind to the **move constructor** of `std::string`, `basic_string(basic_string&& str)`. That constructor gives `b` the value `a` had before the call. How it gets there is up to the implementation: for a long string it typically takes over `a`'s heap buffer; for a short string held inside the object (the small-string optimisation, an implementation technique) it copies the few characters. Either way `a` is still an object of type `std::string`, its lifetime has not ended, and its destructor will run at the end of its scope. ## The standard's wording: valid but unspecified The library introduction says that, unless a type specifies otherwise, a moved-from object of a standard library type is placed in a **valid but unspecified state**, and the `basic_string` move constructor repeats it: `str` "is left in a valid but unspecified state". The definition has two halves: - **valid**: the object's invariants hold and every operation on it behaves as specified for its type; - **unspecified**: the standard does not say what value it has, so a portable program must not depend on it. The standard's own example uses `std::vector<int>`: in that state `x.empty()` can be called unconditionally, while `x.front()` can be called only if `x.empty()` returned `false`. ## What you may do with `a` | Operation on `a` | Allowed without a check? | Why | |---|---|---| | destructor (end of scope) | yes | valid objects can always be destroyed | | `a = "level_04";` or `a = other;` | yes | assignment has no precondition on the old value | | `a.clear()` | yes | no precondition; afterwards `a` is known to be empty | | `a.size()`, `a.empty()` | yes | no precondition; the result is simply unknown in advance | | `a.front()`, `a.back()`, `a.pop_back()` | no | each requires `!a.empty()` | | reading the characters and expecting the old text | no | the value is unspecified | So the rule of thumb is: **treat a moved-from object like one you have just received from a function that documents nothing about its value**. Give it a new value, or query it before using anything with a precondition. ## Reusing a moved-from string in a loop The pattern that bites in real code is a string reused as an accumulator. A batching loop appends asset names to `batch`, moves the full batch into a vector, then keeps appending. If the loop relies on the moved-from `batch` being empty, it works on the two big implementations and is still not portable. Calling `batch.clear()` right after the move costs almost nothing and turns "unspecified" into "empty". 1. Move the value out: `batches.push_back(std::move(batch));` 2. Reset it to a known state: `batch.clear();` 3. Continue appending as if it were new. ## Checking before reading When code genuinely needs to look at a moved-from object, query it first, exactly as you would any string whose contents you do not know: - `if (!a.empty()) use(a.front());` is correct whatever the move left behind; - `a.size()` tells you the current length, whatever it is; - comparing `a == ""` is well-defined too, and simply answers the question. The destructor matters as well: because `a` is still alive, it releases whatever `a` holds at the end of its scope. That is why a moved-from object must stay valid rather than "half destroyed": the language will still call its destructor, and the library may still call its assignment operator, for example when a container moves a new value into a slot that was moved from earlier. ## What implementations actually do Both major standard libraries leave a moved-from `std::string` empty: the libc++ that ships with Apple clang prints a size of 0 for short and long strings alike, and the libstdc++ move constructor sets the source's length to 0 in its header. That is an implementation's choice. The standard deliberately does not require it, because a requirement written for one type would fix behaviour that should stay free for others. ## Common mistakes - Treating any use of a moved-from object as undefined behaviour and refusing even to assign to it. - Believing the opposite: that the standard guarantees "empty" and appending is therefore safe. - Calling `front()` or `pop_back()` on it without checking `empty()` first. - Assuming `a` and `b` now share one buffer; they are two independent strings. A few standard types do specify their moved-from state exactly, `std::unique_ptr` being the best known; `std::string` is not one of them.

  • Is calling a.size() on a moved-from std::string allowed?
    Yes. `size()` has no precondition, so it is well-defined on any valid string; only its result is unknown in advance. libc++ and libstdc++ return 0, but portable code reads it as "some length". Members with preconditions, such as `front()`, `back()` and `pop_back()`, are the ones that need `!a.empty()` checked first.
  • Why does the standard not simply require a moved-from std::string to be empty?
    The library states one general rule for all its types, valid but unspecified, and only spells out an exact moved-from state where a type needs one, such as `unique_ptr` being null. Leaving the value open keeps implementations free to pick the cheapest correct move. Both major libraries happen to empty the string, but the standard does not promise it.

  • The standard guarantees that a moved-from std::string is empty.
  • Any use of a moved-from object, even assigning to it, is undefined behaviour.
  • After the move, a and b share the same character buffer.
  • A moved-from string must not be destroyed because it no longer owns anything.
  • Calling front() on a moved-from string is fine because it was non-empty before.