在 C++ 中 return 多个大对象的最佳方法是什么?

What is the best way to return multiple large objects in C++?

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

#include <tuple>
#include <iostream>

struct A {
    A() {}

    A(const A& a) {
        std::cout << "copy constructor\n";
    }

    A(A&& a) noexcept {
        std::cout << "move constructor\n";
    }

    ~A() {
        std::cout << "destructor\n";
    }
};

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...\n\n";
    auto [a1, b1] = foo();
    std::cout << "\n";

    std::cout << "calling bar...\n\n";
    auto [a2, b2] = bar();
    std::cout << "\n";

    std::cout << "calling quux...\n\n";
    auto [a3, b3] = quux();
    std::cout << "\n";

    std::cout << "calling mumble...\n\n";
    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 结构吗?元组构造函数可能是那里的移动构造函数,因为它在从函数 returned 的表达式中触发,即因为结构 a 即将不存在。

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

My main question is why foo() ends up copying? RVO should elide the tuple from being copied but shouldn't the compiler be smart enough to not copy the A struct? The tuple constructor could be a move constructor

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

what it going on with quux(). I didnt think that additional std::move() call was necessary but I don't understand why it ends up causing an additional move to actually occur i.e. I'd expect it to have the same output as bar().

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