Note that there are some explanatory texts on larger screens.

plurals
  1. POCapturing reference variable by copy in C++0x lambda
    primarykey
    data
    text
    <p>According to the answers and comments for <a href="https://stackoverflow.com/q/5470174/320418">this question</a>, when a reference variable is captured by value, the lambda object should make a copy of the referenced object, not the reference itself. However, GCC doesn't seem to do this.</p> <p>Using the following test: </p> <pre class="lang-c++ prettyprint-override"><code>#include &lt;stddef.h&gt; #include &lt;iostream&gt; using std::cout; using std::endl; int main(int argc, char** argv) { int i = 10; int&amp; ir = i; [=] { cout &lt;&lt; "value capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); [&amp;] { cout &lt;&lt; "reference capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); return EXIT_SUCCESS; } </code></pre> <p>Compiling with GCC 4.5.1, using <code>-std=c++0x</code>, and running gives the following output:</p> <pre class="lang-none prettyprint-override"><code>value capture i: 10 ir: -226727748 &amp;i: 0x7ffff27c68a0 &amp;ir: 0x7ffff27c68a4 reference capture i: 10 ir: 10 &amp;i: 0x7ffff27c68bc &amp;ir: 0x7ffff27c68bc </code></pre> <p>When captured by copy, <code>ir</code> just references junk data. But it correctly references <code>i</code> when captured by reference.</p> <p>Is this a bug in GCC? If so, does anyone know if a later version fixes it? What is the correct behavior?</p> <h3>EDIT</h3> <p>If the first lambda function is changed to</p> <pre class="lang-c++ prettyprint-override"><code>[i, ir] { cout &lt;&lt; "explicit value capture" &lt;&lt; endl &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl &lt;&lt; "ir: " &lt;&lt; ir &lt;&lt; endl &lt;&lt; "&amp;i: " &lt;&lt; &amp;i &lt;&lt; endl &lt;&lt; "&amp;ir: " &lt;&lt; &amp;ir &lt;&lt; endl &lt;&lt; endl; }(); </code></pre> <p>then the output looks correct:</p> <pre class="lang-none prettyprint-override"><code>explicit value capture i: 10 ir: 10 &amp;i: 0x7fff0a5b5790 &amp;ir: 0x7fff0a5b5794 </code></pre> <p>This looks more and more like a bug.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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