shared_ptr with vector

boost, c++, shared-ptr

Solution

Probably just `std::vector<MyClass>`. Are you

- working with polymorphic classes or

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

Problem

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?

Original source