I see a lot of cases where people use vector<shared_ptr<T>>
. When and why would you use shared_ptr<vector<T>>
instead? For me, the latter seems more efficient both in performance and memory-usage. Is it wrong to share a single vector of objects across the application?
Thanks
This use: vector<shared_ptr<T>>
will allow you to pass instances of type T
from this vector to some other parts of code without fear that they will not be freed. Even if your vector will no longer exist.
shared_ptr<vector<T>>
on the other hand protects only vector, its elements of type T
are not protected against memory leaks. I assume here that T
is of pointer type, if T
is non-pointer, then of course you don't have a problem with making memory leak here. Well someone could make T = shared_ptr<T>
actually.
Its actually more common to use vector<shared_ptr<T>>
, I don't really remember using shared_ptr<vector<T>>
.
The point is to never keep, in your code, bare pointers to allocated memory, always keep them in some kind of smart pointer. Its perfectly fine if you implement your own allocate/deallocate mechanism, i.e.. using RAII.
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