r/cpp • • Jul 23 '26

State of "moved-from" objects

Hi, I recently decided to try writing a C++ blog.

I often see the popular claim that moved-from objects are in a "valid but otherwise unspecified state", but I don't think that statement is entirely precise, and my blog post is about that. I would really appreciate any feedback!

Article: https://www.laminowany.dev/p/the-state-of-moved-from-objects-in-c/

10 Upvotes

54 comments sorted by

View all comments

Show parent comment

3

u/jwakely libstdc++ tamer, LWG chair Jul 27 '26 edited Jul 27 '26

I don't know why people struggle with this so much.

"Valid but unspecified state" means some state that is valid for an object of that type, but not required to be any particular state (if the type supports more than one valid state, which some don't, e.g. nullptr_t or monostate don't). In other words, it hasn't got broken invariants. Your "minimal" definition already requires more than some types support (types which are not assignable are possible, and types which can't be destroyed are possible).

It just means the object still follows the rules of the object model and lifetime model. It's within its lifetime, calling member functions isn't inherently UB (some member functions might have preconditions that restrict when you can call them, but that's true whether or not the object has been moved from), any vtable hasn't been overwritten by random data, ... it hasn't been turned into radioactive waste or uninitialized memory that no longer represents an object. And the value of the object is a valid one for that type, so e.g. if it's an optional it doesn't contain a value but have the has_value flag set to false, because that is not a valid state for optional. An invariant of optional is that the flag is true if and only if there is a contained value.

We don't actually need a precise definition of "valid" in isolation because that isn't the term that's used. It's not that an object must be "valid" and must also be in "an unspecified state". It's a single definition where both adjectives refer to the state: a state which is valid but unspecified.