When a container is moved, it is placed in a "valid but unspecified state" according to the C 0x standard draft. In such a situation, it's crucial to understand how to reuse the moved container correctly.
Consider the following code snippet:
std::vector<int> container; container.push_back(1); auto container2 = std::move(container); // ver1: Do nothing //container2.clear(); // ver2: "Reset" container = std::vector<int>() // ver3: Reinitialize container.push_back(2); assert(container.size() == 1 && container.front() == 2);
According to the standard, option ver3, which involves reinitializing the moved container, is the correct approach. This is because, after a move operation, an object is placed in an unspecified state.
The standard defines a "valid but unspecified state" as follows:
"an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type"
This means that the moved-from object remains live and can be operated on, but only if preconditions are met. In the case of a vector, clearing the container with clear() has no preconditions and returns it to a known state.
Therefore, the recommendation is to use clear() to reset a moved container and return it to a usable state.
Option ver2, which involves calling clear() on the moved container, is also valid. However, it may lead to optimizations assuming the moved container is empty. Using clear() ensures that the container is returned to a known state, regardless of optimizations.
Option ver1, which involves doing nothing, is not recommended. This is because the container is in an unspecified state after the move and may exhibit unexpected behavior.
The above is the detailed content of How Should You Reuse a Moved C Container?. For more information, please follow other related articles on the PHP Chinese website!