简体   繁体   中英

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 . Does this mean all I have to do is change my vector to:

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> . 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.

Along that point, it may make sense to wrap your entire 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.

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 ).

Don't immediately jump to shared pointers. You might be better suited with a simple pointer container if you need to avoid copying objects.

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