gpt4 book ai didi

c++ - 传递堆栈对象的所有权而不重复

转载 作者:行者123 更新时间:2023-12-02 10:05:25 25 4
gpt4 key购买 nike

第三方库有 API Huge computeHuge() .它返回对象本身,而不是引用/指针。我无法控制对象或 API。

我有两个类(class):

class Bar {
Huge h;
Bar(Huge &huge): h(huge);
}

class Foo {
Bar b;

Foo() {
Huge h = computeHuge();
b = Bar(h);
}

不幸的是,这种设计(暂时)导致了一个巨大对象的两个拷贝:一个拷贝存在于 Foo 中。构造函数,另一个存在于 Bar 中目的。一旦 Foo构造函数退出,只有一个拷贝,但我需要构造函数内的内存加倍。由于 h可能是数百 GB,这很重要。

解决此问题的一种方法是使 Foo h 的所有者:
class Bar {
Huge &h;
Bar(Huge &huge): h(huge);
}

class Foo {
Bar b;
Huge h;

Foo() {
h = computeHuge();
b = Bar(h);
}

这确实成功地消除了 h 的两个拷贝。 ,但在我的应用程序中并没有真正意义: Bar是正确的持有 h .
我怎样才能:
  • 调用 computeHuge()Foo构造函数
  • Bar保留 h 的所有权
  • 无需两份 h在内存中?
  • 最佳答案

    如果 Huge是可移动的,这不会产生任何拷贝:

    class Bar {
    Huge h;
    Bar(Huge huge): h(std::move(huge)) {} // move huge into its final place, h
    };

    class Foo {
    Bar b;

    Foo() {
    Huge h = computeHuge();
    b = Bar(std::move(h)); // move h into constructor argument
    // h cannot be used here anymore
    }
    };

    出于调试目的,这是一个(很小的) Huge不能复制,只能感动。每次复制尝试都是编译器错误:
    struct Huge {
    Huge() = default;
    Huge(Huge&& other) { std::cout << "move "; }
    Huge(const Huge& other) = delete;
    Huge& operator=(Huge&& other) { std::cout << "move= "; return *this; }
    Huge& operator=(const Huge& other) = delete;
    };

    关于c++ - 传递堆栈对象的所有权而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442172/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com