std::move 在 RValue 引用函数上不起作用

std::move Not Working on RValue Reference Function

提问人:Kiran Thilak 提问时间:9/17/2019 最后编辑:OblivionKiran Thilak 更新时间:9/17/2019 访问量:759

问:

在尝试学习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,但在这里它仅作为参考移动。有人可以解释一下这里发生了什么。

C++ C++11 向量 标准 右值引用

评论

1赞 rafix07 9/17/2019
你有没有把(偷走的内容)搬进去?不,那么为什么你认为这个向量的大小应该为 0 呢? 仅转换为 Rvalue ref。valuefoomove
2赞 j6t 9/17/2019
正如斯科特·迈耶斯(Scott Meyers)喜欢说的那样:不前进(也不前进)。std::movestd::forward

答:

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>&&foovecNumbersmain

如果你真的想移动(窃取)内容,你必须调用移动构造函数或移动赋值运算符。在内部,你可以这样做:vecNumbersfoo

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>vecNumbersvaluefoo