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?

Jojodmo
  • 23,357
  • 13
  • 65
  • 107
1hunch1kill
  • 522
  • 4
  • 12
  • 13
    That's a lambda, and you're binding the current instance to it. – Zeta Apr 08 '14 at 07:20
  • 5
    It means you capture `this`. –  Apr 08 '14 at 07:22
  • 1
    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) – Andre Kostur Apr 08 '14 at 14:09
  • Everything that has the form [](){} is a lambda (yes, that's new to C++11). – Marius Bancila Apr 09 '14 at 11:56
  • Automatic type deduction with the `auto` keyword and the null pointer literal `nullptr` are also C++11. – emsr Apr 09 '14 at 16:40

1 Answers1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 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? – luk32 Apr 08 '14 at 14:33
  • 1
    @luk32 it overloads the built-in operator, just as user-declared operator overloads do. – Mike Seymour Apr 08 '14 at 15:10
  • 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". – Ethouris Apr 09 '14 at 11:46