Home >Backend Development >C++ >What Conditions Ensure the Validity of a Moved-From Object in C 11?
Valid State of "Moved From" Objects in C 11
Question:
In C 11, when an object is moved from, it enters an unspecified state. What conditions should such a "moved from" object satisfy to remain valid?
Answer:
The validity of a moved-from object is defined by the type's specification and documentation.
For standard library types, moved-from objects are placed in an unspecified but valid state, meaning they meet all standard requirements for the type, unless otherwise stated. Users must query the state to determine valid operations.
For developer-defined types, you define and document what constitutes a valid state and permissible operations for moved-from objects.
In the context of the pimpl idiom example provided:
class Foo { std::unique_ptr<FooImpl> impl_; };
You could specify that moving from a Foo object invalidates the operation do_stuff, making it undefined behavior. This is reasonable because moving implies no further operations can be performed on the moved-from object.
Alternatively, you could define a specific state for moved-from Foo objects, ensuring that the concept requirements of the standard library are still met. This would allow you to use moved-from Foo objects with the standard library without undefined behavior.
Note that the standard library concepts do not consider moved-from objects. Therefore, if moved-from objects do not remain in a valid state according to the relevant concept, using them with the standard library will result in undefined behavior.
The above is the detailed content of What Conditions Ensure the Validity of a Moved-From Object in C 11?. For more information, please follow other related articles on the PHP Chinese website!