g++ 在某个类成员未初始化时不发出警告

g++ doesn't warn when some class member is not initialized

本文关键字:警告 初始化 成员 g++      更新时间:2023-10-16

我有以下代码,我希望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的构造函数没有初始化成员吗?

GCC使用-Weffc++选项("有效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上的现场演示。