假设以下是 vector 的 [] 运算符实现:
template<class T>
T& Vector<T>::operator[](unsigned int index)
{
if(index >= my_capacity) {
if(1 /*something to check that [] operator was used in RHS (means read)*/) cout << "Out of bounds read" << endl;
else cout << "Out of bounds write" << endl; //means write operation
}
return arr[index];
}
Run Code Online (Sandbox Code Playgroud)
现在在 main() 里面:
Vector<int> v(5, 10); //initializes 5 values, each = 10
Run Code Online (Sandbox Code Playgroud)
现在,假设我有 2 个陈述
int ans = v[10]; //First
v[10] = 1; //Second
Run Code Online (Sandbox Code Playgroud)
我基本上想得到的输出为:
Out of bounds read
Out of bounds write
Run Code Online (Sandbox Code Playgroud)
我应该如何决定“if”中的条件相同(对 [] 运算符的调用是读还是写)?任何人都可以帮助我吗?非常感谢!
你不能。
解决方法是不返回引用,而是返回一个代理对象,该对象可以检测是读取还是写入。但是因为 C++ 还不允许重载operator .,这样的代理永远不可能是完全透明的。
我的经验是不值得。
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |