Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's quite simple. Say I have a vector:</p> <pre><code>std::vector&lt;int&gt; vec; </code></pre> <p>I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to <code>std::for_each</code>:</p> <pre><code>std::for_each(vec.begin(), vec.end(), SomeFunctor()); </code></pre> <p>In C++03, <code>SomeFunctor</code> was free to be able to <em>modify</em> the parameter it gets. Sure, <code>SomeFunctor</code> could take its parameter by value or by <code>const&amp;</code>, but there's no way to <em>ensure</em> that it does. Not without doing something silly like this:</p> <pre><code>const std::vector&lt;int&gt; &amp;vec_ref = vec; std::for_each(vec_ref.begin(), vec_ref.end(), SomeFunctor()); </code></pre> <p>Now, we introduce <code>cbegin/cend</code>:</p> <pre><code>std::for_each(vec.cbegin(), vec.cend(), SomeFunctor()); </code></pre> <p>Now, we have syntactic assurances that <code>SomeFunctor</code> cannot modify the elements of the vector (without a const-cast, of course). We explicitly get <code>const_iterator</code>s, and therefore <code>SomeFunctor::operator()</code> will be called with <code>const int &amp;</code>. If it takes it's parameters as <code>int &amp;</code>, C++ will issue a compiler error.</p> <hr> <p>C++17 has a more elegant solution to this problem: <a href="http://en.cppreference.com/w/cpp/utility/as_const" rel="noreferrer"><code>std::as_const</code></a>. Well, at least it's elegant when using range-based <code>for</code>:</p> <pre><code>for(auto &amp;item : std::as_const(vec)) </code></pre> <p>This simply returns a <code>const&amp;</code> to the object it is provided. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload