class CheckPointer {
public:
CheckPointer(int * mbeg, int * mend) :
beg(mbeg), end(mend), curr(mbeg) {}
// subscript operator
int & operator[] (const size_t pos) {
if (beg + pos < beg) {
throw out_of_range("ERR: before beg!");
}
if (beg + pos >= end)
throw out_of_range("ERR: end or past end!");
return *(const_cast<int *>(beg + pos));
}
private:
const int * beg;
const int * end;
int * curr;
};
我已經爲類CheckPointer定義了一個下標運算符。由於@參數pos是size_t類型,我無法檢查用戶是否已傳遞正值或負值。 Howerver我嘗試寫的代碼做的,而不是束縛檢查和它的作品:添加size_t類型值的指針
if (beg + pos < beg) {
throw out_of_range("ERR: before beg!");
}
我不知道爲什麼它的工作原理...可以在任何一個可以幫助我?
謝謝你考慮我的問題!
欲瞭解更多信息:
環境:Eclipse CDT的,Ubuntu的10.04
測試代碼:
int iarr[6] = {1, 2, 3, 4, 5, 6};
CheckPointer cp(iarr, iarr+6);
// subscript
cout << cp[2] << endl;
cout << cp[5] << endl;
cout << cp[-2] << endl; // error: before beg
測試code_output:
terminate called after throwing an instance of 'std::out_of_range'
what(): ERR: before beg!
3
6
FWIW,這是一個壞主意。錯誤指針是代碼中的一個** bug **,它們不應該導致異常(這是一個意外的,但並非沒有準備就緒的情況)。不應該爲壞指針做好準備,應該阻止它們。如果你想改善你的代碼的可調試性,你可以使用'assert'來代替(或者事實上,依賴於系統的調試器)。另外,'const_cast'在這裏只是語義錯誤。不要存儲指向'const'的指針,存儲'const'指針。最後,'beg'從不使用。去掉它。 –
@Konrad Rudolph:感謝您的評論:) – Tianyi