title: c++ - Why a std::vector<>::const_reference can cast to a non-const pointer?
body: <p>In g++ , element access operator for const std::vector&lt;> is defined as follows: (<code>/usr/include/c++/7.1.1/bits/stl_vector.h</code>)</p>
  
  <pre><code>/**
     *  @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-&gt;_M_impl._M_start + __n);
    }
  </code></pre>
  
  <p>But the following code compiles with no problem using <code>g++ -c const-vector.cpp -Wall -pedantic</code></p>
  
  <pre><code>#include &lt;vector&gt;
  
  void sum(const std::vector&lt;int&gt;&amp; data){
    int *ptr;
    ptr = (int*) &amp;data[0];
    if (data.size()&gt;2) 
      for (unsigned int i=1;i&lt;data.size();i++) 
        ptr[0]+=ptr[i];
  return;}
  </code></pre>
  
  <p>So I'm changing the contents of the <code>vector</code> passed by const reference.</p>
  
  <p>According to <a href="http://en.cppreference.com/w/cpp/container/vector/operator_at" rel="nofollow noreferrer">cppreference.com</a> , <code>operator[]</code> is overloaded:</p>
  
  <pre><code>reference       operator[]( size_type pos );
  const_reference operator[]( size_type pos ) const;
  </code></pre>
  
  <p>In which case compiler will take the second overload?</p>