Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

G++ -Wshadow doesn't warn about static member shadowing

Once again I lost some hours because of mere stupidity which could have been recognized by the compiler. This is the source code in question:

class f {
    static int mVar;
    int g(int x) { int mVar=3; return x+mVar; }
};
int f::mVar = 1;

The problem is, that I accidentally added int in front of mVar. When I compile this with: g++ -c -Wall -Wextra -Wshadow shadowtest.cpp I don't get any warning, about the local mVar shadowing the static member mVar.

But if I don't declare the member variable to be static, then g++ correctly issues a warning:

class f {
    int mVar;
    f(int rVar) : mVar(rVar) {};
    int g(int x) { int mVar=3; return x+mVar; }
};

compile with g++ -c -Wall -Wextra -Wshadow shadowtest2.cpp gets:

shadowtest2.cpp:5:24: warning: declaration of ‘mVar’ shadows a member of ‘f’ [-Wshadow]
     int g(int x) { int mVar=3; return x+mVar; }
                        ^
shadowtest2.cpp:3:9: note: shadowed declaration is here
     int mVar;
         ^

Tested with g++ 4.9.2 and 5.2.1.

Is this correct behavior or a bug? Why?

Edit: I filed a bug report here: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68374

Edit 2018-02-12: Doesn't warn in these versions:

g++-4.9 (Debian 4.9.4-2) 4.9.4
g++-5 (Debian 5.4.1-4) 5.4.1 20161202
g++-5 (Debian 5.5.0-8) 5.5.0 20171010
g++-6 (Debian 6.3.0-18) 6.3.0 20170516
g++-6 (Debian 6.4.0-12) 6.4.0 20180123
g++-7 (Debian 7.2.0-16) 7.2.0
g++-7 (Debian 7.3.0-3) 7.3.0

but successfully warns in:

g++-8 (Debian 8-20180207-2) 8.0.1 20180207 (experimental) [trunk revision 257435]
like image 636
mxmlnkn Avatar asked Nov 16 '15 15:11

mxmlnkn


1 Answers

This looks potentially like a bug given the description of -Wshadow in the gcc documentation:

Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum.

Especially considering that clang warns for this case. This is basically a quality of implementation issue since this is not ill-formed code. I would file a bug report. Most likely they they will provide a rationale for not warning in this case or they will eventually fix the warnings.

It looks like gcc used to warn about this case if we go all the way back to version 4.5.4 see it live.

like image 107
Shafik Yaghmour Avatar answered Sep 22 '22 18:09

Shafik Yaghmour