Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambdas and the square brackets [duplicate]

Looking at this sample lambda:

[](int factor)->int{return factor*factor;}

Can anybody explain to me what the square brackets in front of a C++11 lambda expression are good for?

like image 448
anhoppe Avatar asked Mar 21 '13 22:03

anhoppe


1 Answers

The square brackets specify which variables are "captured" by the lambda, and how (by value or reference).

Capture means that you can refer to the variable outside the lambda from inside the lambda. If capturing by value, you will get the value of the variable at the time the lambda is created -- similar to passing a parameter to a function by value. If capturing by reference, you will have a reference to the actual variable outside the lambda (and you need to make sure it remains in scope).

Note that inside a class you can capture "this" and then call class methods as you would in a class method.

like image 100
svk Avatar answered Nov 03 '22 11:11

svk