Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - shared_ptr<vector<T>> vs. vector<shared_ptr<T>>

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

like image 847
gipouf Avatar asked Oct 06 '14 07:10

gipouf


1 Answers

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.

like image 74
marcinj Avatar answered Oct 16 '22 21:10

marcinj