c++ - 从方法链中使用的临时 move

标签 c++ move method-chaining temporary-objects

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

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

error: cannot bind rvalue reference of type Bar&& to lvalue of type Bar

是否可以在没有显式 std::move 的情况下进行这项工作?

尝试重载 doThings 并不能解决问题:

error: Bar&& Bar::doThings() && cannot be overloaded

最佳答案

您可以添加 doThings() 的引用限定重载:

struct Bar
    {
    Bar& doThings() &
        {return *this;}

    Bar&& doThings() &&
        {return std::move(*this);}

    std::unique_ptr<int> m_content; // A non-copyable type
    };

关于c++ - 从方法链中使用的临时 move ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51216397/

相关文章:

c++ - 如何从 QVariant 获取用户类型的数据?

python - SWIG 忽略类中的 %mutable;如何解决?

java - Files.move REPLACE_EXISTING 无法解析为变量

c++ - 如何在 C++ 中同时转换右值和左值参数?

c++ - 初始化 vector 的高效而优雅的方法

php - 如何在 PHP5 中构建多 oop 函数

javascript - Chai JS 如何使函数括号可选?

c++ - 为什么我们在使用宏时找不到合适的运算符重载?

C++ 错误 : no match for 'operator>>' in 'input >> Group1->Entrepreneur::Item' |

c# - 如何在 C# 中创建 Fluent Interface 并对某些方法有一些限制?