My advice: Remove this and use the existing implementation of slist<> . IIRC, it will be in C ++ 1x, so your compiler can already support it. Or it could be in boost . Or take it from somewhere else.
Wherever you are, you have all these problems already resolved , probably very well tested , therefore without errors and quickly , and the code using it is easily recognizable (looking at this, many of us would immediately see what it does , because it has been a while, and it will be part of the next standard).
The last time I wrote my own list class was before STL became part of the C ++ standard library.
Well, since you are stuck in the API you have, here is something that might interest you:
class MyObjectList { public: typedef SomeObject value_type; // more typedefs class iterator { public: typedef SomeObject value_type; // more typedefs iterator(SomeObject* pObj = NULL) : pObj_(pObj) {} iterator& operator++() {if(pObj_)pObj_ = pObj_->next;} iterator operator++(int) {iterator tmp(*this); operator++(); return tmp;} bool operator==(const iterator& rhs) const {return pObj_ == rhs.pObj_;} bool operator!=(const iterator& rhs) const {return !operator==(rhs);} value_type& operator*() {return pObj_;} private: SomeObject* pObj_; }; class const_iterator { public: typedef SomeObject value_type; // more typedefs const_iterator(const SomeObject* pObj = NULL) : pObj_(pObj) {} iterator& operator++() {if(pObj_)pObj_ = pObj_->next;} iterator operator++(int) {iterator tmp(*this); operator++(); return tmp;} bool operator==(const iterator& rhs) const {return pObj_ == rhs.pObj_;} bool operator!=(const iterator& rhs) const {return !operator==(rhs);} const value_type& operator*() {return pObj_;} private: const SomeObject* pObj_; }; MyObjectList() : list_() {GetObjectList(&list_;);} ~MyObjectList() {FreeObjectList(list_);} iterator begin() {return list_ ? iterator(list_) : iterator();} const_iterator begin() const {return list_ ? const_iterator(list_) : const_iterator();} iterator end () {return iterator(getEnd_());} const_iterator end () const {return const_iterator(getEnd_());} private: SomeObject* list_; SomeObject* getEnd_() { SomeObject* end = list_; if(list_) while(end->next) end = end->next; return end; } };
Obviously, there is more to this (for example, I believe that the iterators const and non-const should also be comparable), but this is not difficult to add to this.
source share