Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda reinitialize vector - why does it work?

Tags:

c++

lambda

c++14

Why does the following compile?

vector<int> vec;

auto lambda = [ vec (move(vec)) ]() {  //??      
};

How can I re-initialize an already assigned vec variable with vec (move(vec)) ? Doesn't this call the move constructor?

If I write:

vector<int> vec;
vec (move(vec));

this is not valid

like image 926
Albert Avatar asked Jan 08 '23 13:01

Albert


1 Answers

This is called an init-capture. It declaration of a new variable that shadows the above vec. It's used to capture move-only types in lambda expressions:

An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression’s compound-statement, [..]

More info on cppreference.

like image 182
David G Avatar answered Jan 16 '23 11:01

David G