A third-party library has the API Huge computeHuge(). It returns the object itself, not a reference/pointer. I have no control over the object or the API.
I've got two classes:
class Bar {
Huge h;
Bar(Huge &huge): h(huge);
}
class Foo {
Bar b;
Foo() {
Huge h = computeHuge();
b = Bar(h);
}
Unfortunately, this design results (temporarily) in two copies of a huge object: one copy exists in the Foo constructor, and another exists inside the Bar object. Once the Foo constructor exits, there is only one copy, but I need double the memory inside the constructor. Since h could be hundreds of GB, this matters.
One solution to this problem is to make Foo the owner of h:
class Bar {
Huge &h;
Bar(Huge &huge): h(huge);
}
class Foo {
Bar b;
Huge h;
Foo() {
h = computeHuge();
b = Bar(h);
}
This does successfully eliminate having two copies of h, but it doesn't really make sense in my application: Baris the Right Thing to hold h.
How can I:
- Call
computeHuge()in theFooconstructor - Let
Barretain ownership ofh - All without ever needing two copies of
hin memory?