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>
.
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!
new_clone
method), and can only be copied if the object held is copyableconst
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With