vendredi 26 décembre 2014

Wrap STL iterator to use references instead of pointers

I have a class, for example, Point:



class Point {
public:
double x, y;
};


And I have some container, for example PointCloud, that wraps inside std::vector<Point*>:



class PointCloud {
public:
typedef std::vector<Point*>::const_iterator iterator;
iterator begin();
iterator end();
private:
std::vector<Point*> _point
};


Now I can use my class this way:



PointCloud cloud;
for(auto point : cloud) {
std::cout << point->x << std::endl;
}


I want to implement begin() and end() so my iterators return references instead of pointers and I could write my code that way:



PointCloud cloud;
for (auto point : cloud) {
std::cout << point.x << std::endl;
}


Note: operator . instead of -> operator


I have some reasons to do this thing:




  1. compatibility: Firstly I write my class with std::vector<Point> _point and if I change my mind in the future and replace it with std::vector<Point*> _point and users of my class won't need to change something in their code.




  2. it's just safer to work with references.




  3. There is no need to type -> instead of ..




I work with references instead of pointers.


Is it a right thing to do? An if yes, what would be the best way to implement it?


Aucun commentaire:

Enregistrer un commentaire