Narek
Narek

Reputation: 39881

c++ lambda capture the context by reference and also the `this` pointer

Is it possible to capture the context by reference and also the this pointer with a lambda function?

It seems that the code below does not work. How can I do that?

[&, this] () { }

Upvotes: 1

Views: 3833

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

It "works" just fine m8:

#include <iostream>

struct T
{
    int y;

    T() : y(0)
    {
        int x = 0;
        [&, this](){ x = 1; y = 2; }();

        std::cout << x << ' ' << y << '\n';  // 1 2
    }
};

int main()
{
    T t;
}

It's actually redundant to specify this, as & already captures it.

(live demo)

Upvotes: 5

Related Questions