Lambda immutable function: copied captured variables allowed as const?

While trying to answer 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 fragment , and GCC accepts the code .

On the other hand, they 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 as const for immutable lambdas?

+2
source share
1 answer

mutable it doesn't matter here.

In [expr.prim.lambda]:

init , "auto init-capture;"

[dcl.type.simple]:

e , decltype(e), : [...], e id- (5.2.5), decltype(e) - e.

, decltype(j) int. gcc, 79378.

+3

Source: https://habr.com/ru/post/1668824/


All Articles