未初始化某些类成员时,g ++不会发出警告

时间:2018-10-31 08:57:22

标签: c++ gcc

我有以下代码,希望gcc可以在第6行或第17行发出警告,但gcc不会这样做。

zhifandeMacBook-Pro:CppCodeExample zhifan$ cat -n main.cpp
     1  #include <iostream>
     2
     3
     4  class X {
     5  public:
     6      X() {}
     7      int getA() const { return a;}
     8      bool getB() const {return b;}
     9  private:
    10      int a;
    11      bool b;
    12  };
    13
    14
    15  int main(int argc, char *argv[])
    16  {
    17      X x;
    18      std::cout << "hello " << x.getA() << std::endl;
    19      return 0;
    20  }
zhifandeMacBook-Pro:CppCodeExample zhifan$ g++ main.cpp  -Wall -O2 -Wuninitialized 
zhifandeMacBook-Pro:CppCodeExample zhifan$

我可以收到有关类X的构造函数未初始化成员的警告吗?

1 个答案:

答案 0 :(得分:1)

GCC使用-Weffc++选项(“ Effective C ++”选项)发出警告。从4.1.2开始,我已经在所有版本上进行了尝试。

<source>: In constructor 'X::X()':
<source>:6: warning: 'X::a' should be initialized in the member initialization list
<source>:6: warning: 'X::b' should be initialized in the member initialization list
Compiler returned: 0

您可以在Godbolt here上观看现场演示。