用移动语义返回两个对象

Returning two objects with move semantics

本文关键字:两个 对象 移动 语义 返回      更新时间:2023-10-16

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

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

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

afaik应该移动两个对象并触发rvo。

为什么不使用 std::pair<T1, T2>?另请参见http://www.cplusplus.com/reference/utility/pair and http://en.cppreference.com/w/cpp/utility/pair

返回聚合会更简单:

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

,也可以返回一对或元组,而不是定义自己的类型,如果您不介意失去会员名称。