Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
673 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...