从方法链接中使用的临时移动

Move from temporary used in method chaining

本文关键字:移动 方法 链接      更新时间:2023-10-16

我正在尝试做类似的事情:

#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); }