1
如果在拋出後只有const方法被調用,是否仍然未定義行爲來將const從指針轉換爲對象?如果從未調用任何非const方法,是否安全地拋出const
我試圖同時實現了一類,其中解除引用迭代器是與狀態少量和一個指向父對象(下面簡化的)
雖然常量一個代理對象的迭代和爲const_iterator合格的代理只調用父類的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對象 – patchsoft