Reputation: 749
I have an std::vector<std::unique_ptr<SomeClass>>
variable inside a private section of a class. Other parts of the program uses the methods of that class to add elements to the vector. It works, but now I have got a new requirement to allow users of the class remove some elements from the vector as well.
My problem is: I still want to hide the vector from the outside world to keep encapsulation of the class. I thought my methods could just return an iterator to the elements in the vector, but I've read the C++ reference about it and they say, if a vector changes its size, all iterators made before are invalidated. So, my second idea was to return an index of the newly added element, but it is also not good for obvious reasons.
So, my question is: how to make an persistent reference to an object inside a vector, to be used for deleting the object, without exposing the internals of my class too much?
Upvotes: 0
Views: 95
Reputation: 2849
Easy and fast solution:
std::vector<X>
, to std::map<int, X>
or std::unordered_map<int, X>
id
and return it to user. Add element using id
as key in mapid
Upvotes: 3