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 类定义了一个下标运算符。由于@param pos 是 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
测试代码输出:
terminate called after throwing an instance of 'std::out_of_range'
what(): ERR: before beg!
3
6