查找未初始化成员变量的简单方法

2022-01-18 00:00:00 initialization c++ findbugs

我正在寻找一种简单的方法来查找未初始化的类成员变量.

I am looking for an easy way to find uninitialized class member variables.

在 runtime 或 compile time 中找到它们都可以.

Finding them in either runtime or compile time is OK.

目前我在类构造函数中有一个断点,并一一检查成员变量.

Currently I have a breakpoint in the class constructor and examine the member variables one by one.

推荐答案

如果你使用 GCC,你可以使用 -Weffc++ 标志,它会在成员中未初始化变量时生成警告初始化列表.这个:

If you use GCC you can use the -Weffc++ flag, which generates a warnings when a variable isn't initialized in the member initialisation list. This:

class Foo
{
  int v;
  Foo() {}
};

导致:

$ g++ -c -Weffc++ foo.cpp -o foo.o
foo.cpp: In constructor ‘Foo::Foo()’:
foo.cpp:4: warning: ‘Foo::v’ should be initialized in the member initialization list

一个缺点是 -Weffc++ 也会在变量具有适当的默认构造函数时发出警告,因此不需要初始化.当您在构造函数中初始化变量时,它也会警告您,但不会在成员初始化列表中.它还会对许多其他 C++ 样式问题发出警告,例如缺少复制构造函数,因此当您想定期使用 -Weffc++ 时可能需要稍微清理一下代码.

One downside is that -Weffc++ will also warn you when a variable has a proper default constructor and initialisation thus wouldn't be necessary. It will also warn you when you initialize a variable in the constructor, but not in the member initialisation list. And it warns on many other C++ style issues, such as missing copy-constructors, so you might need to clean up your code a bit when you want to use -Weffc++ on a regular basis.

还有一个错误导致它在使用匿名联合时总是给你一个警告,你目前无法解决这个问题,然后关闭警告,可以通过以下方式完成:

There is also a bug that causes it to always give you a warning when using anonymous unions, which you currently can't work around other then switching off the warning, which can be done with:

#pragma GCC diagnostic ignored "-Weffc++"

但总的来说,我发现 -Weffc++ 在捕捉许多常见的 C++ 错误方面非常有用.

Overall however I have found -Weffc++ to be incredible useful in catching lots of common C++ mistakes.

相关文章