c++ - Lambda function capture a variable vs return value? -


i learning c++11 new function lambda function , little confused. read that

 []         capture nothing (or, scorched earth strategy?)  [&]        capture referenced variable reference  [=]        capture referenced variable making copy  [=, &foo]  capture referenced variable making copy, capture variable foo reference  [bar]      capture bar making copy; don't copy else  [this]     capture pointer of enclosing class 

my question capture variable mean , what's difference return value, if want capture variable have return right?

for example:

[] () { int = 2; return a; }  

why not

int [] () { int = 2; return a; } 

you can "capture" variables belong enclosing function.

void f() {     int a=1;     // lambda constructed copy of a, @ value 1.     auto l1 = [a] { return a; };     // lambda contains reference a, same f's.     auto l2 = [&a] { return a; };      = 2;      std::cout << l1() << "\n"; // prints 1     std::cout << l2() << "\n"; // prints 2 } 

you can return captured variable if want, or can return else. return value unrelated captures.


Comments