问题
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?
回答1:
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
).
回答2:
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.
回答3:
Don't immediately jump to shared pointers. You might be better suited with a simple pointer container if you need to avoid copying objects.
来源:https://stackoverflow.com/questions/10790161/shared-ptr-with-vector