简体   繁体   English

带矢量的shared_ptr

[英]shared_ptr with vector

I currently have vectors such as: 我目前有矢量,例如:

vector<MyClass*> MyVector;

and I access using 我使用

MyVector[i]->MyClass_Function();

I would like to make use of shared_ptr . 我想使用shared_ptr Does this mean all I have to do is change my vector to: 这是否意味着我要做的就是将vector更改为:

typedef shared_ptr<MyClass*> safe_myclass

vector<safe_myclass>

and I can continue using the rest of my code as it was before? 我可以继续使用以前的其余代码吗?

Probably just std::vector<MyClass> . 可能只是std::vector<MyClass> Are you 你是

  1. working with polymorphic classes or 使用多态类或
  2. can't afford copy constructors or have a reason you can't copy and are sure this step doesn't get written out by the compiler? 负担不起复制构造函数,或者有您不能复制的原因,并确保编译器不会写出此步骤?

If so then shared pointers are the way to go, but often people use this paradigm when it doesn't benefit them at all. 如果是这样,那么共享指针就是要走的路,但是当人们根本无法从中受益时,人们通常会使用这种范例。

To be complete if you do change to std::vector<MyClass> you may have some ugly maintenance to do if your code later becomes polymorphic, but ideally all the change you would need is to change your typedef. 为了完整std::vector<MyClass>如果您确实更改为std::vector<MyClass> ,则在代码后来变为多态时,可能要进行一些丑陋的维护,但是理想情况下,您需要做的所有更改就是更改typedef。

Along that point, it may make sense to wrap your entire std::vector. 在这一点上,包装整个 std :: vector可能很有意义。

class MyClassCollection {
     private : std::vector<MyClass> collection;
     public  : MyClass& at(int idx);
     //...
 };

So you can safely swap out not only the shared pointer but the entire vector. 因此,您不仅可以安全地交换共享指针,还可以安全地交换整个向量。 Trade-off is harder to input to APIs that expect a vector, but those are ill-designed as they should work with iterators which you can provide for your class. 折衷很难输入到需要向量的API中,但是由于它们与可为您的类提供的迭代器一起使用,因此设计不当。

Likely this is too much work for your app (although it would be prudent if it's going to be exposed in a library facing clients) but these are valid considerations. 这可能对您的应用程序来说是太多的工作(尽管如果将它公开在面向客户的库中是谨慎的),但这是有效的考虑因素。

vector<shared_ptr<MyClass>> MyVector; should be OK. 应该可以。

But if the instances of MyClass are not shared outside the vector, and you use a modern C++11 compiler, vector<unique_ptr<MyClass>> is more efficient than shared_ptr (because unique_ptr doesn't have the ref count overhead of shared_ptr ). 但是,如果的实例MyClass不载体外共享,并且使用现代C ++编译器11, vector<unique_ptr<MyClass>>是比更有效shared_ptr (因为unique_ptr不具有的引用计数开销shared_ptr ) 。

Don't immediately jump to shared pointers. 不要立即跳转到共享指针。 You might be better suited with a simple pointer container if you need to avoid copying objects. 如果需要避免复制对象,则可能更适合使用简单的指针容器

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

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