【问题标题】:Is it safe to cast away const if never call any non-const methods如果从不调用任何非 const 方法,抛弃 const 是否安全
【发布时间】:2015-07-21 18:20:01
【问题描述】:

如果在转换之后只调用 const 方法,那么从指向对象的指针中转换 const 是否仍然是未定义的行为?

我正在尝试为一个类同时实现迭代器和 const_iterator,其中解引用的迭代器是具有少量状态的代理对象和指向父对象的指针(如下所示)

虽然 const 限定代理只调用父级上的 const 方法,但它仍然需要构造函数中的非 const 指针。

class query {
   public:
      int  get (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 for 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 get (int col) const {
         // can be called by both row and const row
         return m_qry->get(m_row, col);
      }

      void set (int col, int v) {
         // cannot be called for 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;
};

我宁愿避免为不同的迭代器使用不同的类,因为这需要大量的代码重复。

如果这不可能,是否还有其他性能良好的替代设计模式?

【问题讨论】:

  • 然而,通过上述设计,编译器将通过默认的复制构造函数接受 const 引用并生成非 const 对象来咬你

标签: c++ stl iterator constants undefined-behavior


【解决方案1】:

在 const 方法中,this 指针是 const 类型。

所以考虑到它被隐式地转换回 const,行为是明确定义的。

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 2019-05-03
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多