Easy way find uninitialized member variables(查找未初始化成员变量的简单方法)
问题描述
我正在寻找一种简单的方法来查找未初始化的类成员变量.
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.
这篇关于查找未初始化成员变量的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找未初始化成员变量的简单方法
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
