Easy way find uninitialized member variables

后端 未结 11 970
时光说笑
时光说笑 2020-11-29 22:20

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

Finding them in either runtime or compile time is OK.

Currently

11条回答
  •  广开言路
    2020-11-29 23:03

    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.

提交回复
热议问题