I have a factory method that creates a bunch of objects and returns pointers to them. Ownership of the objects transfers to the caller:
std::vector<animal*> create_zoo();
This works, but is prone to memory leaks.
auto zoo = create_zoo();
The vector is on the stack and gets cleaned up automatically, the contained objects are not.
Objects of various sub-types are returned. Returing values instead of pointers won't do.
I was thinking to use
std::vector<std::unique_ptr<animal> > create_zoo();
but unique_ptr
don't have copy semantics and I return the vector
by value, which, in theory, creates a copy.
I could put the vector
on the heap to avoid that
std::unique_ptr<std::vector<std::unique_ptr<animal> > > create_zoo();
but this is getting ridiculous.
This should work too:
std::vector<std::shared_ptr<animal> > create_zoo();
This would work, but it doesn't really transfer ownership. The caller has to assume that there might be other pointers to the objects.
I'm open to suggestions. doesn't need to be std::vector
. I'm just looking for a good way of implementing a factory that returns ownership of several objects with modern c++. I'm avoiding boost for now. I'm trying to explore the new c++11 stuff.
std::vector<std::unique_ptr<animal>>
will work fine : returning a function-local value will move it, not copy it (or only if moving is not available).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With