Why does the following code generate a warning when it is compiled with g++ -Wshadow -std=c++14
?
template<typename Function>
void f(Function g) {
int x;
g(0);
}
int main() {
auto g = [](auto x) {};
f(g);
return 0;
}
Compilation (assume this code is saved as lambda_shadow.cc
):
$ g++ -std=c++14 -Wshadow lambda_shadow.cc
lambda_shadow.cc: In instantiation of ‘main()::<lambda(auto:1)> [with auto:1 = int]’:
lambda_shadow.cc:4:6: required from ‘void f(Function) [with Function = main()::<lambda(auto:1)>]’
lambda_shadow.cc:9:6: required from here
lambda_shadow.cc:8:21: warning: declaration of ‘x’ shadows a previous local [-Wshadow]
auto g = [](auto x) {};
^
lambda_shadow.cc:3:7: note: shadowed declaration is here
int x;
^
This warning is strange because g++ seems to follow the dynamic scoping rules. I used g++ version 4.9.2 and 5.2.0, and clang++ 4.6 does not generate any warning.
In addition, I noticed that g++ compiles this code without warnings if a type of the lambda argument is specified (i.e., auto g = [](int x) {};
).
Does anyone know the reason for this behavior? A bug of g++?