Home >Backend Development >C++ >What Can You Do with a Moved-From Object in C ?
What Operations are Permitted on Moved-From Objects?
The C standard defines the behavior of objects that have been moved from. This knowledge is crucial for understanding how certain functions, such as std::swap, work.
Standard Definition
According to the standard (section 17.6.5.15), objects from C standard library types can be moved and are subsequently placed in a "valid but unspecified state."
Implication for Operations
When an object is in an unspecified state, you can perform any operation that does not have preconditions. Preconditionless operations include:
However, operations with preconditions generally cannot be performed without further checking. For example:
Example: std::swap
The std::swap function, as shown in the original question, requires assignment to moved-from objects. This is possible because assignment is a preconditionless operation.
Additional Note: T c = std::move(a) vs. T c(std::move(a))
In the std::swap implementation, a direct move assignment T c = std::move(a) is used instead of a copy constructor T c(std::move(a)). This is done to avoid an unnecessary copy of a, which would result in a performance penalty.
The above is the detailed content of What Can You Do with a Moved-From Object in C ?. For more information, please follow other related articles on the PHP Chinese website!