c++ - Is it safe to cast away const if never call any non-const methods -


is still undefined behavior cast away const pointer object if const methods ever called after cast?

i'm trying implement both iterator , const_iterator class dereferenced iterator proxy object small amount of state , pointer parent object (simplified below)

although const qualified proxy calls const methods on parent still requires non-const pointer in constructor.

class query {    public:       int  (int r, int c) const;       void set (int r, int c, int v);        class iterator {          iterator (query *q, int r) : m_qry(q), m_row(r) {}          row operator* const () { return row(m_qry, m_row); }           query *m_qry;          int m_row;       };        class const_iterator {          const_iterator (const query *q, int r) : m_qry(q), m_row(r) {}           const row operator* const () {             // protected constructor row needs cast             return row(const_cast<query *>(m_qry), m_row);          }           const query *m_qry;          int m_row;       };        iterator       begin() { return iterator(this, 0); }       const_iterator begin() { return const_iterator(this, 0); } };  class row {    friend query;     public:       int (int col) const {          // can called both row , const row          return m_qry->get(m_row, col);       }        void set (int col, int v) {          // cannot called const row          return m_qry->set(m_row, col, v);       }      protected:       row (query *q, int row) : m_qry(q), m_row(r) {}     private:       query *m_qry;       int m_row; }; 

i prefer avoid using different classes differing iterators require considerable code duplication.

if not possible there other alternative design patterns performance?

in const method, this pointer const type.

so given it's implicitly cast const, behaviour defined.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -