Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::ptr_container and std::vector<shared_ptr>

After reading timdays answer to this question I am curious about the difference between boost::ptr_container and a std::vector<shared_ptr>. I was under the impression that a boost::ptr_container had ownership over the pointers given to it, and upon release would call the destructors of all the pointers it contained regardless of other references to its inhabitants. Which is contrary to the purpose of a std::vector<shared_ptr>, which after release would only release the pointers themselves if the ref count was 0?

If this is the case (I assume it isn't), why would even the Boost documentation example compare the two as though they are similar in purpose, and why would timday's answer propose a boost::ptr_container when it is very different to the purpose of a std::vector<shared_ptr>.

like image 758
deceleratedcaviar Avatar asked Jan 29 '11 11:01

deceleratedcaviar


2 Answers

You are right, the two are widely different.

The first difference, as you noticed, is the ownership semantics. The ownership of items in a Pointer Container is NOT shared. In this regard, a boost::ptr_vector<T> is much closer to a std::vector<std::unique_ptr<T>>.

But this is not the only difference!

  • unless explicitly stated in the type, a Pointer Container will not contain any null pointer
  • a Pointer Container has deep copy semantics (using the new_clone method), and can only be copied if the object held is copyable
  • a Pointer Container has deep const semantics, that is if the container is const then one cannot mutate one of its element.

As for why @timday felt compelled to mention Boost Pointer Container, I think it's because he wanted to broaden the question somewhat. Boost Pointer Container are very much like Smart Pointers that could hold multiple objects, and provide a nicer syntax that containers of pointers in general.

Regarding his comparison to a std::vector< boost::shared_ptr<T> > I think it is simply because this is the traditional way of implementing a vector of pointers in the absence of move semantics (no unique_ptr) since auto_ptr cannot be used in STL container. People just don't know about Pointer Containers most of the time...

like image 115
Matthieu M. Avatar answered Sep 30 '22 14:09

Matthieu M.


There are situations where both can be applied: say a bunch of functions act as clients of container, taking pointers to polymorphic objects out and doing operations on them. If the container outlives all the functions, it can be replaced by a pointer container.

Timday answered the question "What is the difference between the following set of pointer[s]" by pointing out an omission in the list.

like image 27
Fred Foo Avatar answered Sep 30 '22 14:09

Fred Foo