Why is std::move named std::move?
Despite its name, std::move(x) does not physically move anything. Instead, it is simply a cast to an rvalue, known specifically as an xvalue. This term contrasts with prvalue, which refers to an expression with a known, fixed value.
The purpose of this naming convention with std::move was not to mislead, but rather to enhance code readability.
Originally, casting an lvalue to an rvalue required the unfamiliar syntax of static_cast
template <class T> void swap(T& a, T& b) { T tmp(static_cast<T&&>(a)); a = static_cast<T&&>(b); b = static_cast<T&&>(tmp); }
By replacing the static_cast with std::move, the code becomes more intuitive and conveys the intent of the function, which is to move values rather than copy them:
template <class T> void swap(T& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); }
The use of std::move allows programmers to clearly see that the values are being moved, even if they may not fully understand the intricate details of rvalues and move semantics.
Furthermore, programmers are free to define their own functions or macros to cast values to rvalues if they prefer. For instance, the following code snippet implements the functionality of std::move using the name set_value_category_to_xvalue:
template <class T> inline constexpr auto& set_value_category_to_xvalue(T&& t) noexcept { return static_cast<std::remove_reference_t<T>&>(t); }
Ultimately, while the generated object code for std::move does not involve any actual movement, it plays a significant role during compilation. It alters which overload of a function is called, potentially leading to the invocation of more efficient move assignment operators defined in classes.
The above is the detailed content of Why is std::move called std::move if it doesn't actually move anything?. For more information, please follow other related articles on the PHP Chinese website!