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

Viewed 427
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?

2 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)
};

There is basically none. It's just there to allow you to give the captured value a custom name.

Note however that this syntax (called init capture) is required when you want to actually move an object into the closure:

std::vector<int> vector;
auto lambda = [vec = std::move(vector)]() { /* the lambda owns the vector now */ });
Related