26

The examples I have found that capture this in a lambda use it explicitly; e.g.:

capturecomplete = [this](){this->calstage1done();};

But it seems it is also possible to use it implicitly; e.g.:

capturecomplete = [this](){calstage1done();};

I tested this in g++, and it compiled.

Is this standard C++? (and if so, which version), or is it some form of extension?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
plugwash
  • 9,724
  • 2
  • 38
  • 51
  • 1
    The answers are correct, but there's a possible reason for using `this->` explicitly, which is to ensure that explicitly captured values are used explicitly. Note that `[](){ calstage1done(); }` would not be legal, because `this` wouldn't be captured; but when capturing `this` explicitly, it's surprising for the function body to _appear_ at a glance not to actually use the captured value: `[this](){ calstage1done(); }`. – Kyle Strand Nov 11 '19 at 20:46
  • I can sort of see this, but at the same time it seems horriblly verbose for what should be a simple task. – plugwash Nov 12 '19 at 08:03
  • 1
    I remember MSVC (maybe only 2015) also having issues with capturing `this` and using it in a lambda which might also be a reason to use it explicitly – Flamefire Nov 12 '19 at 13:20
  • @plugwash: Developers tend to always be lazy and want to minimize things, and language designers are no different. However, verbosity is often required to resolve ambiguity, and that is the case here. – Flater Nov 12 '19 at 14:43

2 Answers2

24

It is standard and has been this way since C++11 when lambdas were added. According to cppreference.com:

For the purpose of name lookup, determining the type and value of the this pointer and for accessing non-static class members, the body of the closure type's function call operator is considered in the context of the lambda-expression.

struct X {
    int x, y;
    int operator()(int);
    void f()
    {
        // the context of the following lambda is the member function X::f
        [=]()->int
        {
            return operator()(this->x + y); // X::operator()(this->x + (*this).y)
                                            // this has type X*
        };
    }
};
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
18

It's completely standard and has been since lambdas were introduced in C++11.

You do not need to write this-> there.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055