Since the broader usage of std::shared_ptr
and std::unique_ptr
to handle memory management came up, I often run into problems of their proper usage in collections like std::vector
. I'm looking for a catalogue of design patterns oder common usages - especially for C++ due to the issue of memory management.
I give an example of what I'm looking for:
If you want to store a collection of objects of some class A
in a std::vector
or other collection (I drop the std
from now on). Furthermore you want to have the owner of the vector
have ownership of all the objects. Then there are at least two safe options for that:
- Use
vector<A>
- Use
vector<unique_ptr<A>>
- Use
vector<shared_ptr<A>>
- Use
vector<A*>
All have advantages and disadvantages like for 1) A has to be assignable and references to objects change if the vector changes.
For 2) I don't want to give unique_ptr<A>
objects to the user unless I really do want to hand the object over to them.
And there are some related questions like: How do I give users of the class storing the vector
the entire collection or the ability to iterate over the objects?
etc....
So is there some reference where I can find this and similar questions analyzed in some detail?
Aucun commentaire:
Enregistrer un commentaire