gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:14:28 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com