Which of the below two lambda functions is correct?
#include <cstdlib>
extern constinit int exit_code { };
int main( )
{
auto lambda_1 { [ &exit_code ]( ) noexcept
{
exit_code = EXIT_FAILURE;
} };
auto lambda_2 { [ ]( ) noexcept
{
exit_code = EXIT_FAILURE;
} };
lambda_1( );
lambda_2( );
return exit_code;
}
GCC warns about &exit_code
:
warning: capture of variable 'exit_code' with non-automatic storage duration
Clang shows an error about it:
error: 'exit_code' cannot be captured because it does not have automatic storage duration
If the above code is not correct (for instance ill-formed), then what is the correct way of making the global variable accessible to a lambda? Is lambda_2
legal? If it's not then why doesn't GCC also warn about the usage of the global variable in lambda_2
? How does it access it without even capturing it?
If none is correct, then how should the above code be designed?
You don't need to capture non-local variables. From lambda:
A lambda expression can use a variable without capturing it if the variable
- is a non-local variable or has static or thread local storage duration (in which case the variable cannot be captured), or
And since exit_code
is a global variable, it can be used withing the lambda's body, without capturing it.