skypjack
skypjack

Reputation: 50540

Non mutable lambda function: are copy-captured variables allowed to be const?

While trying to reply to another question here on SO, I found a difference in how GCC and clang work with lambdas.

Consider the following code:

#include <type_traits>

int main() {
    int i = 0;
    [j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}

In this case, clang rejects the snippet, while GCC accepts the code.

On the other side, both of them accept the code below (for obvious reasons):

#include <type_traits>

int main() {
    int i = 0;
    [j = i]()mutable{ static_assert(std::is_same<decltype(j), int>::value, "!"); }();
}

Are compilers allowed to declare variables captured by copy as const for non-mutable lambdas?

Upvotes: 2

Views: 189

Answers (1)

Barry
Barry

Reputation: 302852

mutable doesn't matter here.

In [expr.prim.lambda]:

An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;”

And from [dcl.type.simple]:

For an expression e, the type denoted by decltype(e) is defined as follows: [...] if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e.

So decltype(j) should be int. This is a gcc bug, reported as 79378.

Upvotes: 3

Related Questions