如何判断vector的[]运算符调用属于右值读还是左值写操作
问题解答
首先明确:你当前给出的单版本operator[](返回T&)的结构下,无法直接在函数体内编写条件判断读写场景。因为operator[]的调用执行时机早于后续的读写操作:函数返回引用后,才会执行赋值(写)或取值(读),函数运行时无法感知后续操作的类型。
要实现你要的区分读写越界的效果,需要采用**代理类(Proxy)**改造operator[]的返回值,通过代理类的运算符重载分别捕获读、写行为。
实现代码示例
#include <iostream> using namespace std; template<class T> class Vector { private: T* arr; unsigned int my_capacity; // 内部代理类,用于捕获[]的读写行为 class WriteReadProxy { Vector& owner_vec; unsigned int access_index; public: WriteReadProxy(Vector& vec, unsigned int idx): owner_vec(vec), access_index(idx) {} // 重载赋值运算符:捕获写操作 T& operator=(const T& value) { if(access_index >= owner_vec.my_capacity) { cout << "Out of bounds write" << endl; } return owner_vec.arr[access_index] = value; } // 重载类型转换运算符:捕获读操作 operator T() const { if(access_index >= owner_vec.my_capacity) { cout << "Out of bounds read" << endl; } return owner_vec.arr[access_index]; } }; public: Vector(unsigned int cap, T init_val): my_capacity(cap) { arr = new T[cap]; for(int i=0; i<cap; i++) arr[i] = init_val; } ~Vector() { delete[] arr; } // 非const对象调用的[]返回代理类 WriteReadProxy operator[](unsigned int index) { return WriteReadProxy(*this, index); } // const对象调用的[]直接返回const引用,统一按读处理 const T& operator[](unsigned int index) const { if(index >= my_capacity) { cout << "Out of bounds read" << endl; } return arr[index]; } }; // 测试main函数 int main() { Vector<int> v(5, 10); int ans = v[10]; // 触发读越界打印 v[10] = 1; // 触发写越界打印 return 0; }
运行效果
编译运行上述代码,输出正好符合你的预期:
Out of bounds read Out of bounds write
补充说明
如果遇到读写结合的操作(比如v[10] += 2),会先触发读越界打印、再触发写越界打印,符合实际对该位置先读再写的操作逻辑。
内容的提问来源于stack exchange,提问作者love_to_code
相关产品推荐
相关产品推荐

