Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
1hunch1kill Avatar asked Apr 08 '14 07:04

1hunch1kill


People also ask

What does \= mean in C?

It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A. *=

What is the use of this in C?

This function is being used to wait for the user's input. This C function returns 0 after terminating the C programme or main function. The function or method block is closed with these curly braces.


1 Answers

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.

like image 145
Mike Seymour Avatar answered Oct 04 '22 10:10

Mike Seymour