在调用右值对象的getter方法时获取右值

Get an rvalue when calling a getter method on an rvalue object

本文关键字:方法 获取 getter 对象 调用      更新时间:2023-10-16

假设我有以下代码:B中有一个复制构造函数,它调用一个方法来复制a的资源。

现在我也有了一个move构造函数。在这种情况下,不应该复制a,而只是从现有的a中"窃取"资源。因此,我还实现了一个接受右值的init。当然,当我尝试用参数b.a调用它时,这是一个左值。

是否有办法调用这个方法?

class A{
    A(const A&& a){
        // 'steal' resources from a
    }
    void init(A& a){
       // init this A from another A by copying its resources
    }
    void init(A&& a){
      // init this A from another A stealing its resources and tell the other a, it must not destroy resources upon destruction
    }
};
class B{
    A a;
    B(B& b){
      a.init(b.a)          
    }
    B(B&& b){
      a.init(b.a); // How to call init(A&& a)?  
    }
};

b.a是左值,所以您需要应用std::move:

a.init(std::move(b.a));

注释: 为什么bB(B&& b)主体的左值

这里,参数类型B&& b仅仅意味着,当用右值调用B(const B& b)时,将选择此构造函数重载。

B make_B() { return B(); }
B b1(make_B());            // B(B&&) chosen
B b2(b);                   // B(const B&) chosen

但是形参本身是左值,因为它有一个名称。std::move所做的只是使它的参数看起来像右值。