Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lambda captures

Tags:

c++11

lambda

When accessing variable a inside "run" lambda, I observe the address to be different than the 'a' in main. This is only happening with this kind of lambda nesting. Is this to be expected? I can only reproduce with this kind of non-trivial nesting.

I inspect the address with gdb inside the lambda as this->__a

Printing a inside the lambda with gdb yields garbage, while the lambda has the captured parameters inside the lambda object, that's why puzzles me that this->__a has different address than a:

(gdb) p &a
$5 = (unsigned int *) 0x7fffffffdce8
(gdb) p *this
$6 = {__a = @0x7fffffffdde8}
(gdb) p a
$7 = 4207233
(gdb) p this->__a
$8 = (unsigned int &) @0x7fffffffdde8: 2

When the lambda is not nested I recall observing the same address.

Currently seen this behavior in g++-4.5 (Debian 4.5.3-3) 4.5.3 and g++-4.6 (Debian 4.6.0-10) 4.6.1 20110526 (prerelease)

#include <string>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <stdexcept>
#include <stdint.h>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
    unsigned a = 0;
    vector<int> vi = {0, 1, 2, 3, 4 };

    auto run = [&](int& i) {
        // inside this lambda &a is not the same as the &a in the first line
        cout << "i: " << i << endl;
        a++;
        cout << "a: " << a << endl;

    };
    for_each(vi.begin(), vi.end(), [&](int& xi) {
        run(xi);
    });

    cout << "a: " << a << endl;
}

I filled the following bugreport in a related to this question issue: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49651

like image 695
piotr Avatar asked Nov 26 '22 11:11

piotr


1 Answers

It was a bug in gcc. It is fixed now.

See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49651

like image 137
Philipp Claßen Avatar answered Nov 28 '22 02:11

Philipp Claßen