很容易找到未初始化的成员变量 [英] Easy way find uninitialized member variables

查看:336
本文介绍了很容易找到未初始化的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找找到未初始化类成员变量的简单方法。



运行时或编译时两种方法都可以。


$ b $

如果使用GCC,您可以使用

code> -Weffc ++ 标志,当变量未在成员初始化列表中初始化时生成警告。这:

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

导致:

  $ g ++ -c -Weffc ++ foo.cpp -o foo.o 
foo.cpp:在构造函数'Foo :: Foo()':
foo.cpp:4:warning :'Foo :: v'应该在成员初始化列表中初始化

一个缺点是 -Weffc ++ 也会在变量具有正确的默认构造函数时发出警告,因此不需要初始化。它也会在构造函数中初始化变量时发出警告,但不会在成员初始化列表中。它警告许多其他C ++风格问题,如缺少副本构造函数,所以你可能需要清理你的代码一点,当你想使用 -Weffc ++



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

  #pragma GCC诊断忽略-Weffc ++

总的来说,我发现 -Weffc ++ 在捕捉大量的通用C ++时非常有用错误。


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

Runtime or compile time both methods OK.

Currently breakpoint in class constuctor and watch variable one by one.

解决方案

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() {}
};

Leads to:

$ 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

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++"

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

这篇关于很容易找到未初始化的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆