在右值对象上调用getter方法时获取右值 [英] Get an rvalue when calling a getter method on an rvalue object

查看:77
本文介绍了在右值对象上调用getter方法时获取右值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose, I have the following code. There's a copy constructor in B which calls a method which copies the resources of a.

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

Now I also have a move constructor. In this case, a should not be copied but just "steal" the resources from an existing a. Therefore, I also implemented an init taking an rvalue. But of course, when I try to call it with parameter b.a, this is an lvalue...

有没有一种方法可以调用此方法?

Is there a way to call this method?

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:

b.a is an lvalue, so you need to apply std::move:

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


注意:但是为什么bB(B&& b)主体中的左值?


Note: But why is b an lvalue in the body of B(B&& b)?

在这里,参数类型B&& b只是意味着在使用右值调用此构造函数重载时,例如,将选择B(const B& b).

Here, the parameter type B&& b simply means that this constructor overload will be chosen over, say, B(const B& b) when invoked with an rvalue.

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

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

But the parameter itself is an lvalue because it has a name. All std::move does is make its argument look like an rvalue.

这篇关于在右值对象上调用getter方法时获取右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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