Search code examples
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:

    • Entries in the container cannot be NULL.
    • Values you get from iterators and functions are references to the type, not pointers to the type.
    • Working with many standard algorithms can be... tricky. And by "tricky", I mean broken. Pointer containers have their own built-in algorithms.

    However, the fact that pointer containers know that they're containers of pointers, they can offer some new functionality:

    • A clone member function that performs a deep copy, via the use of a certain "Cloneable" concept on the type of the object.
    • The ability of a container to release ownership of its objects (after a shallow copy, for example).
    • Built-in functions to transfer ownership to other containers.

    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.