In g++ , element access operator for const std::vector<> is defined as follows: (/usr/include/c++/7.1.1/bits/stl_vector.h
)
/**
* @brief Subscript access to the data contained in the %vector.
* @param __n The index of the element for which data should be
* accessed.
* @return Read-only (constant) reference to data.
*
* This operator allows for easy, array-style, data access.
* Note that data access with this operator is unchecked and
* out_of_range lookups are not defined. (For checked lookups
* see at().)
*/
const_reference
operator[](size_type __n) const _GLIBCXX_NOEXCEPT
{
__glibcxx_requires_subscript(__n);
return *(this->_M_impl._M_start + __n);
}
But the following code compiles with no problem using g++ -c const-vector.cpp -Wall -pedantic
#include <vector>
void sum(const std::vector<int>& data){
int *ptr;
ptr = (int*) &data[0];
if (data.size()>2)
for (unsigned int i=1;i<data.size();i++)
ptr[0]+=ptr[i];
return;}
So I'm changing the contents of the vector
passed by const reference.
According to cppreference.com , operator[]
is overloaded:
reference operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;
In which case compiler will take the second overload?