jeudi 30 mars 2017

Lambda expression with empty capture

I've encountered an interesting case (at least for me) when using lambdas and was wondering whether it is a compiler bug or something allowed by the standard feature.

Let's cut to the chase. Having sample code:

const int controlValue = 5;
std::vector<int> vect{ 0, 1, 2, 3 };
const auto result = std::any_of(vect.begin(), vect.end(), [](const int& item)
{
    return item == controlValue;
});

Notice that controlValue variable is not captured by the lambda expression. In the cppreference for lambda expressions it is stated that:

[] - captures nothing

Using VS2015 for compilation of the above code gives an error which is not surprising:

error C3493: 'controlValue' cannot be implicitly captured because no default capture mode has been specified

However, when using MinGW with gcc 4.8.2 same example compiles and works. Some online compilers including gcc 5.4.0, clang 3.8.0 give similar result.

When controlValue looses its const then all tested compilers give the error all expect (that the variable is not captured which is fine).

Which of the compilers is standard compliant in this case? Does this mean that some optimizations or other "hacks" are used for const variables here? Maybe something is captured implicitly? Could anyone explain the situation happening here?

Aucun commentaire:

Enregistrer un commentaire