首页 > 解决方案 > std::move 不适用于 RValue 引用函数

问题描述

在尝试学习 std::move 和 rvalue reference 时,我遇到了以下问题:

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++11vectorstdrvalue-reference

解决方案


std::move仅转换为 Rvalue 引用。

foo将 Rvalue ref 设为vector<int>。由move(vecNumbers)你得到vector<int>&&。在里面foo你只需访问vecNumbersmain. 您没有执行任何更改此向量内容的操作。

如果您真的想移动(窃取)内容,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>被调用,它移动vecNumbersvalue里面foo


推荐阅读