The STL vector template defines elements of access to elements of both const and non-const variants, for example:
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);}
When does the compiler decide to use one version on top of another? The vector itself is not defined as const, and elements are not stored in it. Therefore, two functions are specified:
A f(int i) const
{ return myVector[i]; }
A f(int i)
{ return myVector[i]; }
My understanding is that the first will call the const version of the [] operator and return const A. The second will call the non-constant version and return the non-constant A?
For me, the first version of f () seems to be “correct” for writing, since the function does not change anything, but the caller may be surprised that it returns constant A. Of course, if I wanted to return const A, I need to define f () as:
const A f(int i) const
{ return myVector[i]; }
To say, no matter who writes to the caller, to expect the const to return.
, ? const, boost:: ptr_vector, std::vector? ? ? ?