用移动语义返回两个对象
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。
为什么不使用 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;
}
,也可以返回一对或元组,而不是定义自己的类型,如果您不介意失去会员名称。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何在Qt中连接来自不同窗口的两个对象?
- C++两个对象,其中包含指向同一数组不同部分的指针
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- C++:在另外两个对象之间共享一个对象
- 在单元测试中,如何在不使用 operator== 的情况下比较两个对象,这可能会错过新成员?
- 同一类的两个对象相互引用
- 将类对象传递给两个对象
- 如何调用运算符函数添加两个对象?
- 让一个名为A的类.传递以下两个对象有什么区别:(a)obj1和(b)obj1()
- 比较矢量迭代中的两个对象C
- 当我有两个对象时<<如何重载运算符?(有关系)
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 使用指针将两个对象(每个都与一个类)相关联
- 比较类的两个对象之间的数据