According to the answers and comments for this question, 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.
Using the following test:
#include <stddef.h>
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char** argv)
{
int i = 10;
int& ir = i;
[=]
{
cout << "value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
[&]
{
cout << "reference capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
return EXIT_SUCCESS;
}
Compiling with GCC 4.5.1, using -std=c++0x
, and running gives the following output:
value capture
i: 10
ir: -226727748
&i: 0x7ffff27c68a0
&ir: 0x7ffff27c68a4
reference capture
i: 10
ir: 10
&i: 0x7ffff27c68bc
&ir: 0x7ffff27c68bc
When captured by copy, ir
just references junk data. But it correctly references i
when captured by reference.
Is this a bug in GCC? If so, does anyone know if a later version fixes it? What is the correct behavior?
EDIT
If the first lambda function is changed to
[i, ir]
{
cout << "explicit value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
then the output looks correct:
explicit value capture
i: 10
ir: 10
&i: 0x7fff0a5b5790
&ir: 0x7fff0a5b5794
This looks more and more like a bug.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…