c++ - overloading operator-> for iterator where underlying container doesn't store real objects -
i've diagonal
class serves principle diagonal. minimize space storing {begin: point, size: int}
instead of storing list of point
s
now algorithms easy implement if can make diagonal iterable. wrote 1 point_iterator
class point_iterator{ friend class diagonal; const diagonal& _diagonal; size_t _position; public: typedef point_iterator self_type; typedef point value_type; typedef point reference;//< returning value instead of reference typedef boost::shared_ptr<point> pointer;//< can never return pointer typedef std::random_access_iterator_tag iterator_category; typedef boost::int32_t difference_type; public: pointer operator->(){return pointer(new point(_diagonal.at(_position)));} point operator*(){return _diagonal.at(_position);}
as there no point
stored anywhere in container cannot return reference or pointer through iterator. in cases i've create point (copyable) object , return.
so reference typedef not reference. okay ?
i cannot implement operator->()
returns point
object, has return pointer, point*
or pointer like. , cannot return new point(operator*())
because user need delete them. using shared_ptr
instead. okay ?
i couldn't use unique_ptr
because c++11. , scoped_ptr
not copyable.
you can return object storing point
, providing overload of operator->()
: calls operator->()
chained until gets result return pointer:
class point_pointer { private: point m_p; public: point_pointer(point p): m_p(p) {} pointer const* operator->() { return &this->m_p; } }; point_pointer point_iterator::operator->() const { return point_pointer(this->operator*()); }
although approach work, storing point
in iterator preferrable performance reason , object life-time point of view.
Comments
Post a Comment