问题描述
在我的课本中,矢量push_back move实现的实现是:
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 );
}
我对std :: move的理解是,它基本上是静态的,将项目强制转换为右值引用.那么,为什么在最后一行中,当x已经作为右值引用传入时,他们必须使用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?
推荐答案
x
是右值引用,但必须遵循的经验法则是:如果有名称,则为左值 .因此,您必须应用 std :: move
将其类型转换为右值.如果您省略了 std :: move
,则将复制 x
而不是将其移至目标位置.可以在已解释的右值引用中找到更多信息.
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.
这篇关于矢量push_back移动实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!