我需要从一个函数返回两个类对象,我看到一些代码执行以下操作:
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。
最佳答案
为什么不直接使用 std::pair<T1, T2>
?另见 http://www.cplusplus.com/reference/utility/pair和 http://en.cppreference.com/w/cpp/utility/pair
关于c++ - 返回具有移动语义的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196497/