在调用右值对象的getter方法时获取右值
Get an rvalue when calling a getter method on an rvalue object
假设我有以下代码: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)
主体的左值
这里,参数类型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++为构建时间获取QDateTime的可靠方法
- 获取从C++中同一类中的构造函数调用的方法返回的值
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 如何从ECS中的模板方法获取组件?
- 如何在没有实例的情况下获取非静态方法的类型?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 使用内置的Windows方法获取文件夹的内容
- 使用push_back方法获取智能指针矢量时应用崩溃
- 方法获取字符串
- 我可以从静态基方法获取当前类类型 ID 吗?
- 填充字符数组的最佳方法(获取与cin.getline)
- 如何从指针到方法获取类(对象类型)
- 以下方法获取绝对值的速度是多少
- 从 Arduino 库中的方法获取私有布尔属性
- C 便携式方法获取u8字符串文字的值表示
- Qt QNetworkAccessManager 或其他方法获取 html 状态代码而不获取页面 contenet
- 在堆栈和堆上使用较低级别的方法获取缓冲区的长度
- WinDivert 1.0.5 DivertRecv() 方法 获取最后一个错误 998
- cgicc - cgi.getElements(),哪种方法?获取或发布
- 从静态方法获取类的类型