为什么 std::move 复制右值或 const 左值函数参数的内容?

Why does std::move copy contents for a rvalue or const lvalue function argument?

如果我在当前范围内的堆栈对象上使用 std::move,内容将移动到目标,留下来源为空。

#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main()
{
    std::string str("Whosebug");

    std::vector<std::string> vec;
    vec.emplace_back(std::move(str));
    std::cout << "vec[0]: " << vec[0] << std::endl;

    std::cout << "str: " << str << std::endl;
}

结果:

vec[0]: Whosebug
str: 

如果我将 std::move 用于右值或 const 左值函数参数,则会复制内容。

#include <iostream>
#include <memory>
#include <vector>
#include <utility>

void process_copy(std::vector<int> const & vec_)
{
    std::vector<int> vec(vec_);
    vec.push_back(22);
    std::cout << "In process_copy (const &): " << std::endl;
    for(int & i : vec)
        std::cout << i << ' ';
    std::cout << std::endl;
}

void process_copy(std::vector<int> && vec_)
{
    std::vector<int> vec(vec_);
    vec.push_back(99);
    std::cout << "In process_copy (&&): " << std::endl;
    for(int & i : vec)
        std::cout << i << ' ';
    std::cout << std::endl;
}

int main()
{
    std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    process_copy(std::move(v));

    std::cout << "In main: " << std::endl;
    for(int & i : v)
        std::cout << i << ' ';
    std::cout << std::endl;
    std::cout << "size: " << v.size() << std::endl;
}

结果:

In process_copy (&&): 
0 1 2 3 4 5 6 7 8 9 99 
In main: 
0 1 2 3 4 5 6 7 8 9 
size: 10

为什么 std::move 的行为不同?

如果值绑定到变量,即使它被声明为右值引用 (&&),您也需要使用 std::move。即它应该是:

void process_copy(std::vector<int> && vec_)
{
    std::vector<int> vec(std::move(vec_));
    ...
}

您的矢量实际上是复制的,而不是移动的。这样做的原因是,尽管声明为右值引用,vec_ 表示函数体内的 lvalue 表达式。因此 std::vector 的复制构造函数被调用,而不是移动构造函数。这样做的原因是,vec_ 现在是一个命名值,而右值不能有名称,所以它折叠成一个左值。由于这个原因,以下代码将无法编译:

void foo(int&& i)
{
    int&& x = i;
}

为了解决这个问题,您必须通过调用 std::move(vec_).

再次使 vec_ nameless