简体   繁体   English

“[this]”在C ++中意味着什么

[英]What does “[ this ]” mean in C++

When I was reading the Cocos2dx 3.0 API, I found something like this: 当我阅读Cocos2dx 3.0 API时,我发现了这样的事情:

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? 是什么[this]是什么意思? Is this new syntax in C++11 ? 这是C++11新语法吗?

What does [this] means? 这是什么意思?

It introduces a lambda - a callable function object. 它引入了一个lambda - 一个可调用的函数对象。 Putting this in the brackets means that the lambda captures this , so that members of this object are available within it. this放在括号中意味着lambda 捕获 this ,以便该对象的成员可以在其中使用。 Lambdas can also capture local variables, by value or reference, as described in the linked page. Lambda还可以按值或引用捕获局部变量,如链接页面中所述。

The lambda has an overload of operator() , so that it can be called like a function: lambda有一个operator()的重载,因此可以像函数一样调用它:

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

which will run the code defined in the body of the lambda. 它将运行lambda体中定义的代码。

Is this new syntax in C++11? 这是C ++ 11中的新语法吗?

Yes. 是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM