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

When I read 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 ?

+45
c ++ syntax api c ++ 11 cocos2d-x
Apr 08 '14 at 7:18
source share
1 answer

What does it mean]?

It represents lambda , the function's called object. Putting this in brackets means that lambda captures this , so that members of this object are accessible inside it. Lambdas can also capture local variables by value or by reference, as described on the linked page.

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

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

which will run the code defined in the lambda body.

Is this new syntax in C ++ 11?

Yes.

+57
Apr 08 '14 at 7:22
source share



All Articles