从方法链接中使用的临时移动
Move from temporary used in method chaining
我正在尝试做类似的事情:
#include <vector>
#include <memory>
struct Bar
{
Bar& doThings()
{return *this;}
std::unique_ptr<int> m_content; // A non-copyable type
};
struct Foo
{
Foo& append(Bar&& obj)
{
objects.push_back(std::move(obj));
return *this;
}
std::vector<Bar> objects;
};
int test()
{
Foo test;
test.append(std::move(Bar{}.doThings())) //Ok
// Not ok
.append(Bar{}.doThings())
;
}
错误:无法将类型
Bar&&
的右值引用绑定到类型Bar
的左值
是否可以在没有显式 std::move 的情况下完成这项工作?
尝试重载 doThings 并不能解决问题:
错误:
Bar&& Bar::doThings() &&
不能重载
您可以添加 ref 限定的重载doThings()
:
struct Bar
{
Bar& doThings() &
{return *this;}
Bar&& doThings() &&
{return std::move(*this);}
std::unique_ptr<int> m_content; // A non-copyable type
};
问题是,当您从函数返回实例时,您没有右值。
但是,有一种方法可以根据对象的右值/左值重载函数:
Bar& doThings() & {return *this;}
Bar doThings() && {return std::move(*this); }
相关文章:
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 使用移动语义:右值引用作为方法参数
- 在C++中使用移动语义的正确方法是什么?
- 方法冗余移动调用的移动语义
- 从方法链接中使用的临时移动
- 唯一 ptr 将所有权移动到包含对象的方法
- 是否有任何常规方法可以通知 STL 移动和复制构造函数?
- 在Cython中使用移动方法时的汇编误差
- 将对象从一个 std::d eque 移动到另一个的更好方法
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- 有没有更好的方法来移动窗口
- C++移动数组元素的正确方法aligned_storage
- 移动或不从 r 值引用限定方法移动
- 如何使用方法在SDL2中的键按键上移动矩形
- 将shared_ptr移动到shared_ptr指向的对象上调用的方法
- 如何在模板方法内从参数包中移动unique_ptr
- 有没有一种方法可以在不使用std ::移动的情况下初始化类构建类的类
- 有没有一种非重复的方法允许程序员在成员初始化的复制和移动语义之间进行选择
- 将模板方法移动到派生中断编译
- 为什么析构函数禁用隐式移动方法的生成