c++ - G++ -Wshadow 不警告静态成员阴影

标签 c++ static g++ member shadowing

由于编译器可以识别的纯粹愚蠢,我再次浪费了一些时间。这是有问题的源代码:

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

问题是,我不小心添加了 intmVar 前.当我编译它时:g++ -c -Wall -Wextra -Wshadow shadowtest.cpp我没有收到任何关于本地 mVar 的警告隐藏静态成员 mVar .

但如果我不将成员变量声明为静态,则 g++ 会正确发出警告:

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

g++ -c -Wall -Wextra -Wshadow shadowtest2.cpp 编译得到:

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;
         ^

使用 g++ 4.9.2 和 5.2.1 测试。

这是正确的行为还是错误?为什么?

编辑:我在这里提交了错误报告:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68374

编辑 2018-02-12:在这些版本中不发出警告:

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

但成功警告:

g++-8 (Debian 8-20180207-2) 8.0.1 20180207 (experimental) [trunk revision 257435]

最佳答案

鉴于 -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.

特别是考虑到 clang 会针对这种情况发出警告。这基本上是一个实现质量问题,因为这不是格式错误的代码。我会归档 a bug report .他们很可能会提供在这种情况下不警告的理由,或者他们最终会修复警告。

如果我们一直回到版本 4.5.4 see it live,看起来 gcc 曾经警告过这种情况.

关于c++ - G++ -Wshadow 不警告静态成员阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33739066/

相关文章:

c++ - 使用另一个构造一个具体的 boost::tuple 类型

c++ - 带捕获的比较器

c++ - vs2015 :vc++ for Linux Development no such file

java - 静态初始化 block 跳过

c++ - std::mutex 是否可以轻易破坏?

java - 为什么Java泛型不能用于静态方法?

C++ 链接对象的文件 (G++)

c++ - 错误 : could not convert '<brace-enclosed initializer list>()' from '<brace-enclosed initializer list>' to 'struct'

c++ - 构造错误,调用其方法时找不到对象?

c++ - 同一变量的多个值的 If 语句