Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
user997112 Avatar asked Mar 22 '26 16:03

user997112


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!