Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What differences are between capturing by [&captured] and by [&local = captured] in lambdas?

Tags:

c++

lambda

c++14

vector<int> vec;

//a
auto foo = [&vec](){
    //do something
};

//b
auto foo = [&v = vec](){
    //do something
};

Do I understand it right that only difference between a and b is creation of alias "v" for "vec" in b case or is there more to it?

like image 625
Martin877 Avatar asked Sep 21 '17 15:09

Martin877


1 Answers

In this case there is no real difference. However, if you were to capture by value there would be a difference:

const std::vector<int> vec; // note const

auto foo = [vec]() mutable {
   // can't change vec here since it is captured with cv-qualifiers
};

auto bar = [v = vec]() mutable {
    // can change v here since it is captured by auto deduction rules
    // (cv-qualifiers dropped)
};
like image 192
zen-cat Avatar answered Sep 17 '22 18:09

zen-cat