Boost :: ptr_container and std :: vector <shared_ptr>
After reading the answers boost::ptr_container day to this question, I am interested to know the difference between boost::ptr_container and std::vector<shared_ptr> . I got the impression that a boost::ptr_container had ownership of the pointers provided to it , and after the release, destructors of all pointers were called, it was contained independently of other references to its inhabitants. This contradicts the purpose of std::vector<shared_ptr> , which only releases pointers after release if the number of links was 0?
If this is the case (I believe it is not), why even compare the Boost documentation example, as if they were similar in purpose, and why, in response to one day, suggest boost::ptr_container when it is very different from the std::vector<shared_ptr> target std::vector<shared_ptr> .
You are right, they are different.
The first difference, as you have noticed, is the semantics of ownership. Ownership of items in a pointer container is NOT shared. In this regard, a boost::ptr_vector<T> much closer to a std::vector<std::unique_ptr<T>> .
But this is not the only difference!
- unless explicitly specified in the type, the pointer container will not contain a null pointer
- The pointer container has deep copy semantics (using the
new_clonemethod) and can only be copied if the object to be copied - The pointer container has deep semantics const, that is, if the container is equal to
const, then it cannot mutate one of its elements.
As for why @timday felt compelled to mention the Boost Pointer container, I think because he wanted to expand the question somewhat. The Boost Pointer Container is very similar to smart pointers, which can contain multiple objects and provide a stronger syntax that contains pointer containers in general.
Regarding its comparison with std::vector< boost::shared_ptr<T> > , I think it's just because it is a traditional way to implement a pointer vector in the absence of movement semantics (no unique_ptr ), since auto_ptr cannot be used in the container STL, People just donβt know about pointer containers most of the time ...
There are situations when both methods can be used: let's say a bunch of functions act like a container client, taking pointers to polymorphic objects and performing operations on them. If the container provides all the functions, you can replace it with a pointer container.
The answer to the question "What is the difference between the following set of pointers [s]", indicating the absence of gaps in the list.