为什么尽管参数是R值引用也要使用std :: move [英] Why to use std::move despite the parameter is an r-value reference

查看:40
本文介绍了为什么尽管参数是R值引用也要使用std :: move的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在以下代码中使用 std :: move()感到困惑:

I am confused about using std::move() in below code:

如果我取消注释(2)的行,输出将是: 1 2 3 ,但是如果我取消注释(1)的行,输出将不算什么,这意味着移动 std的构造函数::vector 被调用了!

If I uncomment line at (2) the output would be: 1 2 3 but if I uncomment line at (1) output would be nothing which means that move constructor of std::vector was called!

为什么我们必须在(1)处再次调用 std :: move 才能调用 std :: vector 的move构造函数?

Why do we have to make another call to std::move at (1) to make move constructor of std::vector to be called?

我了解到 std :: move 获得其参数的 r-value ,所以,为什么我们必须获得 r-value (1)中的 r-value ?

What I understood that std::move get the r-value of its parameter so, why we have to get the r-value of r-value at (1)?

我认为(2)中的这一行 _v = rv; 更具逻辑性,应该使 std :: vector 移动构造函数而无需 std进行调用::move ,因为 rv 本身首先是 r-value 引用.

I think this line _v = rv; at (2) is more logical and should make std::vector move constructor to be called without std::movebecause rv itself is r-value reference in the first place.

template <class T>
class A
{
public:
    void set(std::vector<T> & lv)
    {

    }  
    void set(std::vector<T> && rv)
    {           
        //_v = std::move(rv);          (1)
        //_v = rv;                     (2)
    }

private:
    std::vector<T> _v;
};

int main()
{
    std::vector<int> vec{1,2,3};
    A<int> a;

    a.set(std::move(vec));
    for(auto &item : vec)
        cout << item << " ";
    cout << endl;

    return 0;
}

推荐答案

每个命名对象都是Lvalue 有关左值的参考:

Every named object is Lvalue ref about Lvalue:

变量,函数,模板参数对象的名称(自C ++ 20)或数据成员(无论类型如何),例如std :: cin或std :: endl.即使变量的类型是右值引用,由名称组成的表达式是左值表达式

vector 有两个赋值运算符重载,一个重载Lvalue引用,另一个重载Rvalue引用.

vector has two overloads of assignment operator, one for Lvalue reference and another for Rvalue reference.

vector::operator=(const vector&) // copy assignment operator
vector::operator=(vector&&) // move assignment operator

当将Lvalue作为 operator = 的参数传递时,将调用采用Lvalue引用的

重载.此处的详细信息

Overload which takes Lvalue reference is called when Lvalue is passed as argument for operator=. Details here

当一个函数同时具有右值引用和左值引用时重载,右值引用重载绑定到右值(包括prvalue和xvalues),而左值引用重载绑定到左值

when a function has both rvalue reference and lvalue reference overloads, the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues

通过 std :: move(rv); ,您将 rv -左值转换为右值引用,而使用右值引用的 operator = 是叫.否则,左值将绑定到左值参考,并且矢量将被复制而不是被移动.

By std::move(rv); you cast rv - Lvalue to Rvalue reference, and operator= which takes Rvalue reference is called. Otherwise, Lvalue binds to Lvalue reference and vector is copied instead of being moved.

这篇关于为什么尽管参数是R值引用也要使用std :: move的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆