Trying to compile this code:
const int a = 1;
auto lambda = [&]() {
&a;
};
lambda();
On clang++ everything is fine, but g++ gives an error:
error: lvalue required as unary ‘&’ operand
I haven't found anything explaining such behavior. Is it a bug in g++? Or does clang++ miss something?
Lambda Functions in C++11 - the Definitive Guide. A lambda function is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a functor or function pointer ). With lambda, creating quick functions has become much easier, and this means that not only can you start using lambda...
When you capture by reference, the lambda function is capable of modifying the local variable outside the lambda function--it is, after all, a reference. But this also means that if you return a lamba function from a function, you shouldn't use capture-by-reference because the reference will not be valid after the function returns.
When you capture by reference, the lambda function is capable of modifying the local variable outside the lambda function–it is, after all, a reference. But this also means that if you return a lamba function from a function, you shouldn’t use capture-by-reference because the reference will not be valid after the function returns.
Under the final C++11 spec, if you have a lambda with an empty capture specification, then it can be treated like a regular function and assigned to a function pointer. Here's an example of using a function pointer with a capture-less lambda:
It's considered to be a bug in g++: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58894
According to comments, it lasts from GCC 4.5.4 and, at that moment, not fixed in GCC 4.9.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With