Extended Understanding of std::move's Conversion to Rvalues
In C , std::move() plays a crucial role in converting expressions to rvalues (right-value references). However, its implementation can be confusing to grasp. This article aims to provide a clear understanding of the move function and its behavior with both lvalues and rvalues.
std::move()'s Implementation
The std::move() function, as implemented in the MSVC standard library, takes an rvalue reference (&&) argument and returns an rvalue reference. This allows std::move() to handle both lvalues (left-value references) and rvalues effectively.
Rvalue Binding
When std::move() is called with an rvalue, such as a temporary object, the _Arg reference parameter binds directly to the rvalue. This is straightforward since an rvalue reference can bind to an rvalue.
Lvalue Binding
When std::move() is called with an lvalue, the _Arg reference parameter binds to a lvalue reference (Object&). This raises the question of how an rvalue reference can bind to an lvalue.
Reference Collapsing
To understand this behaviour, we need to consider C 11's rules for reference collapsing. These rules state that:
Object & & = Object & Object & && = Object & Object && & = Object & Object && && = Object &&
According to these rules, Object& && is equivalent to Object&, which is a plain lvalue reference that can bind to lvalues.
Effect of remove_reference
std::move() uses std::remove_reference to remove any existing references from the type of the argument, resulting in a typename tr1::_Remove_reference
Advantages of the Implementation
The implementation of std::move() offers several advantages:
Conclusion
std::move()'s implementation is intricately designed to convert expressions to rvalues effectively, handling both lvalues and rvalues with reference collapsing and ensuring a consistent rvalue reference return type. This mechanism plays a critical role in the use of move semantics in C .
The above is the detailed content of How does std::move() convert lvalues to rvalues in C ?. For more information, please follow other related articles on the PHP Chinese website!