4
为什么STL容器定义访问器的const和非const版本?为什么有const和非const访问?
定义const T& at(unsigned int i) const
和T& at(unsigned int)
而不仅仅是非const版本有什么好处?
为什么STL容器定义访问器的const和非const版本?为什么有const和非const访问?
定义const T& at(unsigned int i) const
和T& at(unsigned int)
而不仅仅是非const版本有什么好处?
因为无法在const
矢量对象上调用at
。
如果你只有非const
版本,以下内容:
const std::vector<int> x(10);
x.at(0);
不会编译。使用const
版本可以实现这一点,并且同时防止您实际更改at
返回的内容 - 这是合同规定的,因为矢量为const
。
非const
版本可以在非const
对象上调用,并允许您修改返回的元素,由于该向量不是常量,所以也是有效的。
const std::vector<int> x(10);
std::vector<int> y(10);
int z = x.at(0); //calls const version - is valid
x.at(0) = 10; //calls const version, returns const reference, invalid
z = y.at(0); //calls non-const version - is valid
y.at(0) = 10; //calls non-const version, returns non-const reference
//is valid
的可能的复制[与常量和没有的功能相同 - 什么时候和为什么(https://stackoverflow.com/questions/27825443/same-function-with-const-and-without-when-and -为什么) –