矢量shared_ptr的 [英] shared_ptr with vector
问题描述
我现在有载体,如:
vector<MyClass*> MyVector;
和我Access中使用
and I access using
MyVector[i]->MyClass_Function();
我想利用的shared_ptr
的。这是否意味着所有我需要做的就是改变我的矢量
来:
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>
和我可以继续使用我的code的剩余部分,因为它以前?
and I can continue using the rest of my code as it was before?
推荐答案
也许只是的std ::矢量&lt;&MyClass的GT;
。您
- 与多态类或工作
- 不起拷贝构造函数或者您不能复制并确信这一步没有得到由编译器写出理由吗?
如果这样的话共享指针是要走的路,但往往人们用这种模式时,它不会把这些都受益。
If so then shared pointers are the way to go, but often people use this paradigm when it doesn't benefit them at all.
要完成,如果你更改为的std ::矢量&lt; MyClass的&GT;
你可能有一些丑陋的维护做,如果你的code后来成为多态的,但理想情况下,你需要所有的变化是改变你的typedef。
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 ::向量。
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);
//...
};
所以,你可以放心地换出,不仅共享指针,但整个向量。权衡是难以输入到期望的向量的API,但这些都是设计不当的,因为他们应该用迭代器,你可以为您提供一流的工作。
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.
这篇关于矢量shared_ptr的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!