With c++11 out there, I was asking myself if there is a replacement of the boost::ptr_containers in c++11. I know I can use e.g. a std::vector<std::unique_ptr<T> >
, but I'm not sure if this is a complete replacement. What is the recommended way of handling these cases?
They really solve two similar but different problems.
A pointer container is a way to store objects in a container that just so happen to be pointers to allocated memory rather than values. They do everything in their power to hide the fact that they are a container of pointers. This means:
However, the fact that pointer containers know that they're containers of pointers, they can offer some new functionality:
clone
member function that performs a deep copy, via the use of a certain "Cloneable" concept on the type of the object.They really are quite different concepts. There is a lot of stuff you would have to do manually that pointer containers can do automatically with specialized functions.
If you really need a container of pointers, then you can use containers of unique_ptr
. But if you need to store a bunch of objects that you happen to heap allocate, and you want to play special games with them involving ownership and such, then the pointer containers are not a bad idea.