Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this a known pitfall of C++11 for loops?
    primarykey
    data
    text
    <p>Let's imagine we have a struct for holding 3 doubles with some member functions:</p> <pre><code>struct Vector { double x, y, z; // ... Vector &amp;negate() { x = -x; y = -y; z = -z; return *this; } Vector &amp;normalize() { double s = 1./sqrt(x*x+y*y+z*z); x *= s; y *= s; z *= s; return *this; } // ... }; </code></pre> <p>This is a little contrived for simplicity, but I'm sure you agree that similar code is out there. The methods allow you to conveniently chain, for example:</p> <pre><code>Vector v = ...; v.normalize().negate(); </code></pre> <p>Or even:</p> <pre><code>Vector v = Vector{1., 2., 3.}.normalize().negate(); </code></pre> <p>Now if we provided begin() and end() functions, we could use our Vector in a new-style for loop, say to loop over the 3 coordinates x, y, and z (you can no doubt construct more "useful" examples by replacing Vector with e.g. String):</p> <pre><code>Vector v = ...; for (double x : v) { ... } </code></pre> <p>We can even do:</p> <pre><code>Vector v = ...; for (double x : v.normalize().negate()) { ... } </code></pre> <p>and also:</p> <pre><code>for (double x : Vector{1., 2., 3.}) { ... } </code></pre> <p>However, the following (it seems to me) is broken:</p> <pre><code>for (double x : Vector{1., 2., 3.}.normalize()) { ... } </code></pre> <p>While it seems like a logical combination of the previous two usages, I think this last usage creates a dangling reference while the previous two are completely fine.</p> <ul> <li>Is this correct and Widely appreciated? </li> <li>Which part of the above is the "bad" part, that should be avoided? </li> <li>Would the language be improved by changing the definition of the range-based for loop such that temporaries constructed in the for-expression exist for the duration of the loop?</li> </ul>
    singulars
    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.
 

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