繁体   English   中英

返回带有移动语义的两个对象

[英]Returning two objects with move semantics

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

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。

返回一个聚合会更简单:

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

ReturnObject function() {
    ReturnObject ret;
    return ret;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM