Easy way find uninitialized member variables

后端 未结 11 961
时光说笑
时光说笑 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条回答
  •  旧时难觅i
    2020-11-29 22:59

    Beware! Compiler options proposed here are neither reliable, nor version-independent. Consider the simple example:

    class A {
      int a;
    public:
      void mA() {
        printf("haha");
        ++a;
        int g = 2/a;
        printf("%i\n",g);
      }
    };
    
    int main() {
      A a;
      a.mA();
    }
    

    Compiled with g++ -O3 -Weffc++ -Wuninitialized this thing reports uninitialized on gcc versions up to 4.6 inclusive, and passess happily on 4.7 and 4.8 (tested on MacPorts). Then, curiously, if we remove the printf("haha");, both 4.7 and 4.8 suddenly see uninitialized A::a. Clang is a little better, since it somehow assigns rubbish (instead of convenient 0) to uninitialized vars, so you see their disastrous effect easier/sooner.

    I didn't have much luck in spotting the above uninitialized A::a with valgrind either; maybe the gentlement suggesting valgrind could provide appropriate options to spot this error.

    Bottom line: great question, not much reliable solutions at the moment... (the way I see it).

提交回复
热议问题