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

标签 c++ tuples move-semantics

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

#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 结构吗?元组构造函数可能是那里的 move 构造函数,因为它在从函数返回的表达式中触发,即因为 struct a 将不存在。

我也不太明白 quux() 是怎么回事。我不认为额外的 std::move() 调用是必要的,但我不明白为什么它最终 导致 实际发生额外的 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

不, move 构造函数只能从另一个 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().

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

关于c++ - 在 C++ 中返回多个大对象的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69109774/

相关文章:

c++ - 转换为 `const Y` 不适用于 clang 上的 `R&&`

C++ "const"关键字解释

C++ OpenCV 消除较小的轮廓

c++ - 填充红黑树的最有效方法是什么?

python - Django - 复杂的嵌套列表和元组解包

C++11,返回 vector 函数风格的 move 语义

c++ - sprite在cocos2d-x中无法移动

python - 其键独立于它包含的元素顺序的字典

python - 制作一组元组的有效方法,其中元组的顺序无关紧要

c++ - MPI 和 move 语义