I have two std containers. Both of them with pointers to the same data structure. The first containing all the data and the second one containing only some of the same data. Should I use shared_ptr
or weak_ptr
on the second container?
Firstly, when I read the reference I thought about using unique_ptr
on the first collection. My first collection contains all the data and it's the only one that "owns". Meaning that if the data is not there it should be deleted. But then when I try to create the second collection I didn't know what to do. I created a unique pointer but now I need another pointer to the same element destroying uniqueness, but in fact the real owner was not the new pointer. So I understood (I hope I'm not wrong) that the uniqueness is on the way of reaching elements and not (e.g.) the possibility of delete it. So, shared_ptr
. I have them on my first collection. But now the second one comes up, I thought to use shared_ptr
here too. The ways to access the same data could be both, so the owners are two. But in my case the data is always deleted from the second before. And if I use a weak_ptr
, the number of owners will not increase. In both cases the element will be deleted when the first collection wants. At the end I'm using shared_ptr
because with weak_ptr
I need to lock()
every pointer in every line of code, making it less readable. But what should I really use?
Aucun commentaire:
Enregistrer un commentaire