c++stlc++11unique-ptrboost-ptr-container

stl container with std::unique_ptr's vs boost::ptr_container


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?


Solution

  • 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:

    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.