简体   繁体   中英

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

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, ie. using RAII.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM