简体   繁体   English

C ++ - shared_ptr <vector <T >>与vector <shared_ptr <T >>

[英]C++ - shared_ptr<vector<T>> vs. vector<shared_ptr<T>>

I see a lot of cases where people use vector<shared_ptr<T>> . 我看到很多人使用vector<shared_ptr<T>> When and why would you use shared_ptr<vector<T>> instead? 何时以及为什么要使用shared_ptr<vector<T>> 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. 这个用法: vector<shared_ptr<T>>允许你将类型为T实例从这个向量传递给代码的其他部分而不用担心它们不会被释放。 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. 另一方面, shared_ptr<vector<T>>仅保护向量,其类型T元素不受内存泄漏的保护。 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. 我假设T是指针类型,如果T是非指针,那么当然你没有在这里造成内存泄漏的问题。 Well someone could make T = shared_ptr<T> actually. 那么有人可以让T = shared_ptr<T>

Its actually more common to use vector<shared_ptr<T>> , I don't really remember using shared_ptr<vector<T>> . 实际上使用vector<shared_ptr<T>>更常见,我真的不记得使用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. 使用RAII。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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