36

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
anhoppe
  • 4,287
  • 3
  • 46
  • 58
  • 2
    As an aside, and not mentioned in the other answers, the `[]` also make parsing that there is a lambda expression here really easy: imagine the context where you can have a lambda expression. Can you imagine such a context where it would be valid to have a different use of `[` at the same point? – Yakk - Adam Nevraumont Mar 22 '13 at 13:54

1 Answers1

40

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.

svk
  • 5,854
  • 17
  • 22