提问人:Kiran Thilak 提问时间:9/17/2019 最后编辑:OblivionKiran Thilak 更新时间:9/17/2019 访问量:759
std::move 在 RValue 引用函数上不起作用
std::move Not Working on RValue Reference Function
问:
在尝试学习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";
}
输出
size in Function:2
After Move
size:2
我期望在向量上调用 move 后大小为 0,但在这里它仅作为参考移动。有人可以解释一下这里发生了什么。
答:
3赞
Oblivion
9/17/2019
#1
你对移动的假设是错误的:
std::move 用于指示对象 t 可能被“移出”, 即允许将资源有效地从 T 转移到另一个 T 对象。
具体而言,std::move 会生成一个 xvalue 表达式,该表达式标识 它完全等同于一个 static_cast 右值引用类型。
这并不意味着 vector 的大小应该随着代码变为零。
5赞
rafix07
9/17/2019
#2
std::move
仅强制转换为右值引用。
foo
将 Rvalue ref 设置为 。通过你得到.在里面,你只需访问中定义的。您没有执行任何更改此矢量内容的操作。vector<int>
move(vecNumbers)
vector<int>&&
foo
vecNumbers
main
如果你真的想移动(窃取)内容,你必须调用移动构造函数或移动赋值运算符。在内部,你可以这样做:vecNumbers
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";
}
或者,您可以将 Foo 的签名更改为:
void foo(std::vector<int> value) {
}
然后当你打电话给
foo(std::move(vecNumbers))
的 move 构造函数被调用,它移动到内部。vector<T>
vecNumbers
value
foo
评论
value
foo
move
std::move
std::forward