假设,我有以下代码。 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));
注意:但为什么 b
是 B(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/