
Originally Posted by
roddomi
But I've heard that I should avoid returning handles to object internals because of possible dangling handlers.
Why not just return a couple of const iterators, like,
Code:
class A {
public:
std::vector<int>::const_iterator begin() {return v.cbegin();}
std::vector<int>::const_iterator end() {return v.cend();}
private:
std::vector<int> v;
};
You expose the internal data structure but at least users cannot change the data.
The standard approach to better encapsulation is to offer a getter access method like,
Code:
class A {
public:
int get(int i) {return v[i];}
int size() {v.size();}
private:
std::vector<int> v;
};
Yet another approach is to pass in a functor object. A method (for example operator()) of the functor is called with all ints of the vector one by one. This offers good encapsulation because users never know how the ints are actually stored internally. This approach is sometimes called "inner iteration".
Code:
class A {
public:
template <typename FUNCTOR>
void iterate(FUNCTOR& f) {
for (std::vector<int>::const_iterator p=v.cbegin(); p!=v.cend(); ++p) f(*p);
}
private:
std::vector<int> v;
};
//
class Sum_Functor {
public:
Sum_Functor() : sum(0) {}
int sum;
void operator() (int i) {
sum += i;
}
};
//
A a;
Sum_Functor sf;
a.iterate(sf);
int s = sf.sum;