STL向量模板定义了元素访问器,包括const和非const两种变体,例如:
reference operator[](size_type __n)
{return *(this->_M_impl._M_start + __n);}
const_reference operator[](size_type __n) const
{return *(this->_M_impl._M_start + __n);}
编译器何时决定使用其中一个版本?向量本身没有被定义为const,存储在其中的元素也没有。因此,给定两个函数:
A f(int i) const
{ return myVector[i]; }
A f(int i)
{ return myVector[i]; }
我理解第一个调用operator[]的const版本并返回const A。第二个调用非const版本并返回非const A?
对我而言,f()的第一个版本似乎是应该编写的“正确”版本,因为函数没有改变任何内容,但它可能让调用者惊讶,因为它返回了一个const A。如果我确实需要返回const A,那么我应该定义f()如下:
const A f(int i) const //Note the extra const at the start
{ return myVector[i]; }
这将告诉编写调用者期望返回一个const。
所以这个额外的const是如何出现的?如果我使用boost::ptr_vector而不是std::vector,那么这个额外的const会应用于什么?数据?指针?还是两者都有?