I have a class that represents a list of people.
class AddressBook
{
public:
AddressBook();
private:
std::vector<People> people;
}
I want to allow clients to iterate over the vector of people. The first thought I had was simply:
std::vector<People> & getPeople { return people; }
However, I do not want to leak the implementation details to the client. I may want to maintain certain invariants when the vector is modified, and I lose control over these invariants when I leak the implementation.
What's the best way to allow iteration without leaking the internals?
begin()
andend()
are dangerous because (1) those types are vector iterators (classes) which prevents one from switching to another container such as aset
. (2) If the vector is modified (e.g. grown or some items erased), some or all of the vector iterators could have been invalidated. – rwong Dec 06 '14 at 10:18auto
unless it's not possible, a mechanism which makes one way less dependent of actual iterator type and 2) that is a design decision made and hence has to be documented anyway - sure using vector is dangerous because it's iterators can be invalidated but it's not like that makes vector unusable. Though depending on the exact usage which the OP doesn't mention set/list/... might indeed be a better choice here. – stijn Dec 06 '14 at 10:37const std::vector<T>&
might be the most idiomatic way in C++. – rwong Dec 06 '14 at 12:10