c++ - 返回具有移动语义的两个对象

标签 c++

我需要从一个函数返回两个类对象,我看到一些代码执行以下操作:

class ReturnObject {
public:
ReturnObject(std::vector<int>&& a1, std::map<int, int>&& a2) :
  o1(std::forward<std::vector<int>>(a1)),
    o2(std::forward< std::map<int, int>>(a2)) 
  {
        std::cout << "ctor" << std::endl;
    }

    ReturnObject(ReturnObject&& other) :
     o1(std::move(other.o1)),
     o2(std::move(other.o2)) 
    {
        std::cout << "move ctor" << std::endl;
    }

    std::vector<int> o1;
    std::map<int, int> o2;
};

ReturnObject function() {
    std::vector<int> o1;
    std::map<int, int> o2;

    return {std::move(o1), std::move(o2)};
}

int main()
{
    ReturnObject destination = function();
}

我的问题是:这是返回两个对象的好方法还是这段代码不必要地复杂?

据我所知,这应该移动优化两个对象并触发 RVO。

最佳答案

关于c++ - 返回具有移动语义的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196497/

相关文章:

c++ - Ncurses - "move"及其衍生物删除屏幕内容

c++ - C、C++、python、perl在Web开发中的作用

c++ - 谷歌测试 C++ : Is there a way to read the current console output in a test?

c++ - 使用 Raspberry Pi Camera 和 Open Cv 显示视频时出错

c++ - 需要澄清 direct3D11 中 vector 的概念

c++ - glslang 无法解析内置函数

javascript - Garmin 和 Monkey C "Cannot find symbol ' :setText'. .."

c++ - 这是通用引用吗? std::forward 在这里有意义吗?

java - 将C++映射转换为Java映射

c++ -/MD 和/MDd(使用运行时库)有什么区别?