This is an extension of the question that's already answered here: How to "return an object" in C++?
In summary, I want to instantiate a class in a factory-like method and return its instance like so:
Thing calculateThing() {
Thing thing;
// do calculations and modify thing
return thing;
}
This should work just fine, as long as Thing is trivially copyable. i.e. I could do Thing t2 = calculateThing();
But what if Thing was a composite object? i.e. if I needed to do something like this to build Thing itself:
Thing calculateThing() {
OtherThing ot;
AnotherThing ant;
Thing thing{ot, ant};
// do calculations and modify thing
return thing;
}
Here, the ot and ant go out of scope as calculateThing returns and the thing is no longer a sound object.
One way to address this issue would be to allocate OtherThing and AnotherThing on the heap instead. So that the instances don't get destroyed as they go out of scope. I could even make ot and ant shared pointers, so I don't need to remember to delete these objects. e.g.
Thing calculateThing() {
auto ot = std::make_shared<OtherThing>();
auto ant = std::make_shared<AnotherThing>();
// constructor now takes shared_ptr as args
Thing thing{ot, ant};
// do calculations and modify thing
return thing;
}
With that being said, surely there must exist a design pattern that addresses this exact situation (Builder?). But I can't find any examples, particularly those that use shared pointers. This makes me wonder if I am on a wrong track and maybe there's a better (and maybe correct solution, if mine is wrong).
I'd really appreciate any insights and corrections.