Search code examples
c++boostcontainersshared-ptr

What is the sense of a shared_ptr to a container?


What actually is the point of declaring a boost::shared_ptr to a container like std::vector or std::list?

Here is an example utilizing BOOST_AUTO.

void someFunction()
{
  ...
  BOOST_AUTO(sharedPtrToContainer, boost::make_shared<std::vector<T>>());
  ...
}

Is there any sense if you only need the container locally? What is the benefit? What would be the uses of a shared_ptr to a container?


Solution

  • What actually is the point of declaring a boost::shared_ptr to a container like std::vector or std::list?

    Exactly the same point as using a shared pointer to any object type; it allows you to share ownership of the object with other scopes. It doesn't make any difference that the object happens to be a container.

    Is there any sense if you only need the container locally?

    No; if you only need it locally, then it should be an ordinary automatic object.

    What is the benefit? What would be the uses of a shared_ptr to a container?

    If you need to extend its lifetime beyond the current scope, then you'll need to create and destroy it dynamically, and then its lifetime should be managed by smart pointers.