C++11 lambdas and the square brackets

25,071

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.

Share:
25,071

Related videos on Youtube

anhoppe
Author by

anhoppe

Software Developer in the field of Additive Manufacturing (aka 3D Printing) Worked / working on projects in c++ and C# Also interested in Android (which is just a hobby) Basically clueless ;-)

Updated on March 22, 2020

Comments

  • anhoppe
    anhoppe about 4 years

    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?

    • Yakk - Adam Nevraumont
      Yakk - Adam Nevraumont about 11 years
      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?