What does "[ this ]" mean in C++
Asked Answered
N

1

48

When I was reading the Cocos2dx 3.0 API, I found something like this:

auto listener = [this](Event* event){
    auto keyboardEvent = static_cast<EventKeyboard*>(event);
    if (keyboardEvent->_isPressed)
    {
        if (onKeyPressed != nullptr)
            onKeyPressed(keyboardEvent->_keyCode, event);
    }
    else
    {
        if (onKeyReleased != nullptr)
            onKeyReleased(keyboardEvent->_keyCode, event);
    }
};

What does [this] mean? Is this new syntax in C++11?

Neidaneidhardt answered 8/4, 2014 at 7:18 Comment(5)
That's a lambda, and you're binding the current instance to it.Sinewy
It means you capture this.Nutt
Is there really a point to explicitly mentioning this? Wouldn't it automatically be captured by the reference to onKeyPressed and onKeyReleased (assuming they're members of this). Also a warning, keyboardEvent is now holding a copy of the this pointer... woe betide you if keyboardEvent manages to outlive whatever this is pointing at.... (standard object lifetime issues)Fenelia
Everything that has the form [](){} is a lambda (yes, that's new to C++11).Unroll
Automatic type deduction with the auto keyword and the null pointer literal nullptr are also C++11.Yonkers
T
58

What does [this] means?

It introduces a lambda - a callable function object. Putting this in the brackets means that the lambda captures this, so that members of this object are available within it. Lambdas can also capture local variables, by value or reference, as described in the linked page.

The lambda has an overload of operator(), so that it can be called like a function:

Event * event = some_event();
listener(event);

which will run the code defined in the body of the lambda.

Is this new syntax in C++11?

Yes.

Torsibility answered 8/4, 2014 at 7:22 Comment(3)
I don't want to be PIA, and I am genuinely interested if the term "overload of operator()" is technically correct here? I know ClosureType is a type and has a member function operator(), but I think it is not overloaded at any point, or is it?Duumvir
@Duumvir it overloads the built-in operator, just as user-declared operator overloads do.Torsibility
Well, it may be that when we're talking about an operator that can only be declared as a method of a class, is not "overloaded" because it's by no means defined for that class by default. However for operators it's generally accepted to say that they are being "overloaded" because it's always said about anything callable that is already defined elsewhere. In result, every operator definition is "overloading".Textualist

© 2022 - 2024 — McMap. All rights reserved.