title: Using C++11 range-based for loop correctly in Qt
body: <p>According to <a href="https://www.youtube.com/watch?v=Ov7s0GgBbOQ&amp;list=PLRyNF2Y6sca0UKKZ2PTSwF3WrDjABQdcL&amp;index=27" rel="nofollow noreferrer">this talk</a> there is a certain pitfall when using C++11 range base <code>for</code> on Qt containers. Consider:</p>
  <pre><code>QList&lt;MyStruct&gt; list;
  
  for(const MyStruct &amp;item : list)
  {
      //...
  }
  </code></pre>
  <p>The pitfall, according to the talk, comes from the implicit sharing. Under the hood the ranged-based <code>for</code> gets the iterator from the container. But because the container is not <code>const</code> the iterator will be non-<code>const</code> and that is apparently enough for the container to detach.</p>
  <p>When you control the lifetime of a container this is easy to fix, one just passes the <code>const</code> reference to the container to force it to use <code>const_iterator</code> and not to detach.</p>
  <pre><code>QList&lt;MyStruct&gt; list;
  const Qlist&lt;MyStruct&gt; &amp;constList = list;
  
  for(const MyStruct &amp;item : constList)
  {
      //...
  }
  </code></pre>
  <p>However what about <code>for</code> example containers as return values.</p>
  <pre><code>QList&lt;MyStruct&gt; foo() { //... }
  
  void main()
  {
      for(const MyStruct &amp;item : foo())
      {
      }
  }
  </code></pre>
  <p>What does happen here? Is the container still copied? Intuitively I would say it is so to avoid that this might need to be done?</p>
  <pre><code>QList&lt;MyStruct&gt; foo() { //... }
  
  main()
  { 
      for(const MyStruct &amp;item : const_cast&lt;const QList&lt;MyStruct&gt;&gt;(foo()))
      {
      }
  }
  </code></pre>
  <p>I am not sure. I know it is a bit more verbose but I need this because I use ranged based for loops heavily on huge containers a lot so the talk kind of struck the right string with me.</p>
  <p>So far I use a helper function to convert the container to the <code>const</code> reference but if there is a shorter/easier way to achieve the same I would like to hear it.</p>