std::move() and the Conversion of Expressions to Rvalues
std::move() is a powerful function in C that allows you to move objects from one location to another without copying them. Understanding its implementation can be challenging, but it's essential to掌握 its capabilities.
Implementation Details
The implementation of std::move() in the MSVC standard library uses the std::remove_reference template to convert expressions to rvalues. Here's how it works:
template<class _Ty> inline typename tr1::_Remove_reference< _Ty >:: _Type& && move( _Ty && _Arg ) { return ((typename tr1::_Remove_reference< _Ty >:: _Type&&) _Arg); }
Binding to Lvalues
When you pass an lvalue to std::move(), the _Arg reference parameter binds to the lvalue. However, you cannot directly bind an rvalue reference to an lvalue. To resolve this, the implementation casts the lvalue to an rvalue reference using std::static_cast.
Understanding std::remove_reference
std::remove_reference is used to remove references from types. Here's its implementation:
template<class _Ty> struct _Remove_reference { typedef _Ty _Type; }; template<class _Ty> struct _Remove_reference< _Ty && > { typedef _Ty _Type; }; template<class _Ty> struct _Remove_reference< _Ty &&&&> { typedef _Ty _Type };
Usage with Rvalues
When std::move() is called with an rvalue, std::remove_reference converts T&& to T, resulting in the following function template instantiation:
Object&& move(Object&& arg) { return static_cast<Object&&>(arg); }
The cast is required because named rvalue references are treated as lvalues.
Usage with Lvalues
When std::move() is called with an lvalue, std::remove_reference converts T& to T, resulting in the following function template instantiation:
Object&& move(Object& && arg) { return static_cast<Object&&>(arg); }
Reference collapsing rules provided by the C 11 standard allow Object& && to bind to lvalues. The resulting function effectively casts the lvalue argument to an rvalue reference.
Conclusion
std::move() leverages std::remove_reference and reference collapsing rules to allow the conversion of both lvalues and rvalues to rvalue references. This allows for efficient object movement and optimization of memory usage.
The above is the detailed content of How does `std::move()` convert expressions to rvalues in C ?. For more information, please follow other related articles on the PHP Chinese website!