What does [this] mean in C++? -- StackOverflow

Recently on SO:

What does "[ this ]" mean in C++?

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?

Add a Comment

Comments are closed.

Comments (1)

0 0

andschwa said on Apr 9, 2014 10:57 PM:

That looks to me like a lambda function (a new feature of C++11), see http://en.cppreference.com/w/cpp/language/lambda.

If it is a lambda, then the brackets are used to capture variables for use inside the lambda; particularly,
[this]
captures the 'this' object pointer by value (assuming this code is inside some object instance).

What makes me skeptical is that this lambda has no return value, nor any return statement, and thus should return void; granted, the type of listener is auto, and given void, I bet listener just isn't assigned anything.

Heh, finally saw the link to SO. It actually saves the function to listener, which can then later be called.