This is not a question about putting std::auto_ptr into std::vector.
Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a temporary solution for vectors I have this:
std::auto_ptr<std::vector<std::tr1::shared_ptr<ClassExample> > > fx(....);
which, I suppose, by introducing boost, I will be able to change into this:
std::auto_ptr<std::vectro<boost::unique_ptr<ClassExample> > >f(...);
in order to define strict ownership passing, but it seems to be quite complicated. To simplify it, I can use
std::vector<boost::unique_ptr<ClassExample> > f(...);
as the price for deep copy of the vector is not high, but I am still curious if there is something that I can use like this:
auto_vector<ClassExample> f(...);
meaning that the function is releasing ownership of all the objects and the vector internal data array is not deeply copied.
There's a C++11 solution - it requires an implementation that provides r-value references and has a standard library updated to include move constructors and std::unique_ptr.
Just return std::vector<std::unique_ptr<T>> - that type can't be copied, as std::unique_ptr<T> isn't copyable. The compiler will either use the move constructor when returning, which will not invoke a deep copy or will apply the RVO and elide the construction of a new object.
Without any particular reason as to why you need to maintain a vector of pointers, the first solution would be to ditch all the complexity and go for the simple:
std::vector<Type> f();
Ownership of the objects is unique (the vector owns them), and while the code looks like it is copying the vector on return it will be optimized away in most cases.
If you need the objects inside the vector to be dynamically allocated due to some other requirement (objects must be allocated through a factory, they are pointers to derived types, or they cannot move due to vector growth -- code maintains references/pointers) that you are not showing then I would go for a boost::ptr_vector that will maintain ownership of the contained objects. Again, return by value:
boost::ptr_vector<Type> f();
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