[英]std::move Not Working on RValue Reference Function
While trying to learn std::move and rvalue reference , i just came across the following: 在尝试学习std :: move和rvalue引用时,我遇到了以下问题:
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> vecNumbers;
vecNumbers.push_back(10);
vecNumbers.push_back(20);
foo(std::move(vecNumbers));
std::cout<<"After Move \n";
std::cout<<"size:"<<vecNumbers.size()<<"\n";
return 0;
}
void foo( std::vector<int> &&value)
{
std::cout<<"size in Function:"<<value.size()<<"\n";
}
The Output 输出
size in Function:2
After Move
size:2
I was expecting the size to be 0 after calling move on vector but here it only moved as reference. 我曾期望在vector上调用move之后大小为0,但在这里它仅作为参考移动。 Could someone please explain what is happening here.
有人可以解释一下这里发生了什么。
std::move
only casts to Rvalue reference. std::move
仅强制转换为右值引用。
foo
takes Rvalue ref to vector<int>
. foo
Rvalue ref到vector<int>
。 By move(vecNumbers)
you get vector<int>&&
. 通过
move(vecNumbers)
获得vector<int>&&
。 Inside foo
you just access vecNumbers
which is defined in main
. 里面
foo
你刚刚访问vecNumbers
这是在定义main
。 You didn't do any action which changed the content of this vector. 您没有执行任何更改此向量内容的操作。
If you really want to move (steal) content of vecNumbers
you have to call either move constructor or move assignment operator. 如果您确实要移动(窃取)
vecNumbers
内容, vecNumbers
必须调用move构造函数或move赋值运算符。 Inside foo
you could do this in this way: 在
foo
内部,您可以这样操作:
void foo( std::vector<int>&& value)
{
std::vector<int> v1{std::move(value)}; // invoke move ctor which steals content of value
std::cout<<"size in Function:"<<value.size()<<"\n";
}
or you can change signature of foo to be: 或者您可以将foo的签名更改为:
void foo(std::vector<int> value) {
}
then when you call 然后当你打电话
foo(std::move(vecNumbers))
move constructor of vector<T>
is called which moves vecNumbers
to value
inside foo
. 调用
vector<T>
move构造函数,该vecNumbers
将vecNumbers
移至foo
内部的value
。
Your assumption about move is wrong: 您对移动的假设是错误的:
std::move is used to indicate that an object t may be "moved from", ie allowing the efficient transfer of resources from t to another object.
std :: move用于指示对象“ t”可以“移出”,即允许将资源从t高效转移到另一个对象。
In particular, std::move produces an xvalue expression that identifies its argument t.
特别是,std :: move生成一个xvalue表达式,该表达式标识其参数t。 It is exactly equivalent to a static_cast to an rvalue reference type.
它完全等效于static_cast到右值引用类型。
This doesn't mean the size of vector should become zero with your code. 这并不意味着向量的大小应随您的代码变为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.