在c++中返回多个大对象的最佳方法是什么?



我想返回一个包含std::vectorstd::unordered_map等类型的元组,其中对象可能足够大,我关心不复制。我不确定当返回对象包装在元组中时,复制省略/返回值优化将如何工作。为此,我在下面写了一些测试代码,并对其部分输出感到困惑:

#include <tuple>
#include <iostream>
struct A {
A() {}
A(const A& a) {
std::cout << "copy constructorn";
}
A(A&& a) noexcept {
std::cout << "move constructorn";
}
~A() {
std::cout << "destructorn";
}
};
struct B {
};
std::tuple<A, B> foo() {
A a;
B b;
return { a, b };
}
std::tuple<A, B> bar() {
A a;
B b;
return { std::move(a), std::move(b) };
}
std::tuple<A, B> quux() {
A a;
B b;
return std::move(std::tuple<A, B>{ std::move(a), std::move(b) });
}
std::tuple<A, B> mumble() {
A a;
B b;
return std::move(std::tuple<A, B>{ a, b });
}
int main()
{  
std::cout << "calling foo...nn";
auto [a1, b1] = foo();
std::cout << "n";
std::cout << "calling bar...nn";
auto [a2, b2] = bar();
std::cout << "n";
std::cout << "calling quux...nn";
auto [a3, b3] = quux();
std::cout << "n";
std::cout << "calling mumble...nn";
auto [a4, b4] = mumble();
std::cout << "n";
std::cout << "cleaning up main()n";
return 0;
}

当我运行以上(在VS2019上)时,我得到以下输出:

calling foo...
copy constructor
destructor
calling bar...
move constructor
destructor
calling quux...
move constructor
move constructor
destructor
destructor
calling mumble...
copy constructor
move constructor
destructor
destructor
cleaning up main()
destructor
destructor
destructor
destructor

所以从上面看来bar()是最好的,return { std::move(a), std::move(b) }是最好的。我的主要问题是为什么foo()最终会复制?RVO应该省略元组被复制,但编译器不应该足够聪明,不复制A结构吗?元组构造函数可以是move构造函数,因为它在从函数返回的表达式中触发,即因为structa即将不存在。

我也不太明白quux()是怎么回事。我不认为额外的std::move()调用是必要的,但我不明白为什么它最终导致导致实际发生额外的移动,即我希望它具有与bar()相同的输出。

我的主要问题是为什么foo()最终复制?RVO应该省略元组不会被复制,但编译器不应该足够聪明不复制A结构体?元组构造函数可以是一个移动构造函数

不,move构造函数只能从另一个tuple<>对象构造它。{a,b}是从组件类型构造的,因此复制AB对象。

quux()发生了什么。我没有多余的想法std::move()调用是必要的,但我不明白为什么它结束了导致额外的移动发生,也就是我所期望的具有与bar()相同的输出。

第二次移动发生在移动元组的时候。移动它可以防止在bar()中发生的复制省略。众所周知,整个return表达式周围的std::move()是有害的。

相关内容

最新更新