c++ - 在右值对象上调用 getter 方法时获取右值

标签 c++ move-semantics rvalue-reference

假设,我有以下代码。 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) 主体中的左值?/p>

这里,参数类型 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 所做的只是让它的参数看起来像一个右值。

关于c++ - 在右值对象上调用 getter 方法时获取右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24914817/

相关文章:

c++ - C++11 数组怎么能不存储它的大小呢?

c++ - 如何将 unique_ptr 的 move 构造函数和运算符实现为类的私有(private)成员

c++ - 在构造函数初始化列表上 move shared_ptr

c++ - move 语义将如何改进 "my way"?

c++ - 通过 r 值引用接收后通过引用传递

c++ - 在条件和阻塞调用之间收到 C/C++ SIGINT

c++ - vim折叠cpp和golang代码

c++ - QScopedArrayPointer 保护我的数据,但它仍在泄漏

时间:2019-05-06 标签:c++unique_ptr参数传递

c++ - C++0x 中的 "id"函数