Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++11 and PHP closures require declaring the closed-over variables?

Function literals in both C++ and PHP require programmer to specify which variables they are using from the current lexical context. What's the reason behind this requirement?

I guess it's not meant for the compiler/interpreter, because one can statically infer this information from function literal's body. Is it only for drawing the reader's attention?

like image 508
Aivar Avatar asked Oct 21 '11 10:10

Aivar


1 Answers

For C++11 at least, [=] () {...} will automatically pull in all and only those local variables which the function body uses. (Or, equally, [&]...)

You can specify individual variables to be captured by reference or by value if you have any specific needs beyond this catch-all.

In PHP, variables are created when their name is first used, so I expect the declaration is to make sure no new variables mask the old ones. A bit like the global keyword.

like image 193
spraff Avatar answered Nov 11 '22 00:11

spraff