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.
这篇关于查找未初始化成员变量的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找未初始化成员变量的简单方法
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
