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.
Additionally, 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
loses 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?
EDIT:
Some pointed out that this question is a duplicate of Lambda capturing constexpr object . While the answer there may be somewhat related (points to the odr-use case) the question there is about an error occurring while capturing by ref. The topic here is quite different and focuses on not capturing explicitly a variable at all (although using it in the lambda body).
After looking through more lambda related questions, if someone's interested, I'd point to Using lambda captured constexpr value as an array dimension
which (same as @Barry stated) suggests VS2015 bug and shows that setting the controlValue
variable in the example here to static
fixes the compilation under VS2015.