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/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01