Stefan Stefan - 3 months ago 17
C++ Question

How to return vector of pointers (and ownership) C++11

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.

Answer

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).