Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda doesn't take const variable by reference, why?

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?

like image 363
abyss.7 Avatar asked Oct 27 '13 09:10

abyss.7


People also ask

What is a lambda function in C++11?

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...

What is the difference between lambda function and capture by reference?

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.

What happens if you return a lambda function from a function?

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.

Can a lambda function be assigned to a function pointer?

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:


1 Answers

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.

like image 155
abyss.7 Avatar answered Sep 22 '22 14:09

abyss.7