When "this" is captured by a lambda, does it have to be used explicitly?
Asked Answered
F

2

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?

Flied answered 11/11, 2019 at 15:23 Comment(4)
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(); }.Keim
I can sort of see this, but at the same time it seems horriblly verbose for what should be a simple task.Flied
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 explicitlyGenitourinary
@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.Cheddite
C
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*
        };
    }
};
Cimex answered 11/11, 2019 at 15:31 Comment(0)
T
18

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

You do not need to write this-> there.

Tireless answered 11/11, 2019 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.