Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c++ - Capturing reference variable by copy in C++0x lambda

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This has just been fixed in gcc-4.7 trunk and gcc-4.6 branch. These should be available in gcc-4.7.0 (a while from now - still in stage 1) and gcc-4.6.2 (alas 4.6.1 just came out.)

But the intrepid could wait for the next snapshots or get a subversion copy.

See audit trail for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...