向量<a> vs vector<a*> vs vector<shared_ptr<a> &gt; in C++

时间:2016-02-02 10:40:17

标签: c++ vector shared-ptr

I have a class A which is neither copy-constructable nor assignable. Now I want another class B to hold a vector of A objects. It is also clear that B holds the ownership of these objects.

As I see it, there are (at least) three options:

  1. use vector<A>
  2. use vector<A*>
  3. use vector<shared_ptr<A> >

Is it right that 1. does not work because A is not copy constructable / assignable?

I don't like 2. because I have to make sure that I delete the pointers again.

If I use 3. I feel like this does not clearly represent that B is the owner of the A objects. Also I run into the issue that if I want users of B to delete pointers from this vector they need to pass the element they want to delete by shared_ptr<A>, right?

What would be a clean design decision in this case? Are there any good references on this?

1 个答案:

答案 0 :(得分:2)

  1. 正确; A需要std::vectorunique_ptr一起使用,但是从C ++ 11开始,这很大程度上取决于您需要在向量上使用的操作。
  2. 我同意,我不会再使用原始指针,除非我有一个非常令人信服的理由(在我看来这不是一个)。
  3. 您考虑过{{1}}了吗?这个选项有一个很好的copy-assignable and copy-constructible