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:
vector<A>
vector<A*>
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?
答案 0 :(得分:2)
A
需要std::vector
与unique_ptr
一起使用,但是从C ++ 11开始,这很大程度上取决于您需要在向量上使用的操作。