Understanding Valid States for Moved-from Objects in C 11
Move semantics in C 11 introduce a crucial concept: the state of objects after being moved from. However, the exact conditions that a moved-from object must satisfy can be confusing.
The Issue with pimpl Objects
Consider the pimpl idiom, where a class wraps a pointer to an implementation object. If we move from a Foo object (containing a std::unique_ptr
Standard Library Moved-from States
The C standard defines that moved-from objects of standard library types are placed in an "unspecified but valid state." This means that you can perform operations on them that have valid preconditions.
However, for non-standard types, you must define and document the valid state and operations allowed after being moved from.
Defining the Valid State for pimpl
In the Foo example, we could specify that moving from it renders the do_stuff function invalid. This would prevent us from accidentally invoking it on a moved-from object.
Avoiding Dynamic Allocations
To avoid the overhead of dynamic allocations when checking the valid state, consider using the "null object" pattern. This involves having a default FooImpl that is used when the object is in an invalid state.
Concepts and Moved-from Objects
Finally, note that moved-from objects must still meet the requirements of standard library concepts. If your type doesn't remain in a valid state, using it with standard library functions may result in undefined behavior.
The above is the detailed content of What are the Valid States of Moved-from Objects in C 11 and How to Define Them?. For more information, please follow other related articles on the PHP Chinese website!