代码之家  ›  专栏  ›  技术社区  ›  user877329

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

  •  1
  • user877329  · 技术社区  · 7 年前

    我正试图做类似的事情:

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

    错误: 无法绑定类型的rvalue引用 Bar&& 到类型的左值 Bar

    在没有显式std::move的情况下,是否可以使此工作?

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

    错误: Bar&& Bar::doThings() && 不能超载

    2 回复  |  直到 7 年前
        1
  •  3
  •   Justin    7 年前

    可以添加ref限定的重载 doThings() 以下内容:

    struct Bar
        {
        Bar& doThings() &
            {return *this;}
    
        Bar&& doThings() &&
            {return std::move(*this);}
    
        std::unique_ptr<int> m_content; // A non-copyable type
        };
    
        2
  •  4
  •   R Sahu    7 年前

    问题是,当从函数返回实例时,没有rvalue。

    但是,可以根据对象的rvalue/lvalue重载函数:

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