简体   繁体   中英

vector<A> vs vector<A*> vs vector<shared_ptr<A> > in C++

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. Correct; A needs to be copy-assignable and copy-constructible to be used with std::vector , but from C++11 on, this depends very much on the operations you need to use on the vector.
  2. I agree, I would not use raw pointers anymore unless I had a very compelling reason (and this isn't one in my opinion).
  3. Have you considered unique_ptr ? There's a nice blog post on that option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM