问题
In my textbook, the implementation of the vector push_back move implementation is:
void push_back( Object && x )
{
if( theSize == theCapacity )
reserve( 2 * theCapacity + 1 );
objects[ theSize++ ] = std::move( x );
}
My understanding of std::move is that it basically static casts the item as an rvalue reference. So why on the last line did they have to use std::move( x ), when x was passed in already as an rvalue reference?
回答1:
x
is an rvalue reference, but the rule of thumb you must follow is: if it has a name, it's an lvalue. Therefore you must apply std::move
to convert its type to an rvalue. If you left out the std::move
then x
would be copied instead of moved into its destination. More information can be found in Rvalue References Explained.
来源:https://stackoverflow.com/questions/33205686/vector-push-back-move-implementation