Nested Lambda Grips

When accessing the variable inside the "run" lambda, I see an address different from the "a" in the main one. This only happens with this kind of lambda nesting. Is this to be expected? I can reproduce only this kind of nontrivial investment.

I am checking the address with gdb inside lambda, as this is → __ a

Printing inside a lambda with gdb results in garbage, while a lambda has captured parameters inside a lambda object, so it puzzles me that this → __ a has a different address than:

(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 remember watching the same address.

This behavior is currently under consideration 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 (preerelease)

#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;
}

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

+5
2

:

  • &a .
  • this->__a .

  • this->__a - , &a

, ? this->__a , a, , , - .

-1

All Articles