Search code examples
c++valgrind

no warning for missing ctor initializer list?


This code is missing a constructor initializer list:

#include <cstdio>

struct s { 
    s() {}  // should be s(): m() {}
    int m;
};

int main() {
    struct s *px = new s();
    if (px->m) {
        printf("true\n");
    } else {
        printf("false\n");
    }
    delete px;
    return 0;
}

gcc compiles clean with no warnings:

$ g++ -Wall -Wextra -g -O2 test.cpp

However, valgrind knows that the class member m wasn't initialized:

$ valgrind ./a.out
==10953== Conditional jump or move depends on uninitialised value(s)
==10953==    at 0x400512: main (test.cpp:10)
==10953== 

Why didn't gcc warn about the missing initialization (-Wmissing-field-initializers or -Wuninitialized or -Wmaybe-uninitialized)?

Is there a flag I can pass that will catch this case?


Solution

  • You could add -Weffc++ to catch it (inspired by Scott Meyers book "Effective C++"). Strangely enough it does not refer to any other -W option (and neither does clang++).

    The option is however considered, by some, a bit outdated by now, but in this case, it's finding a real problem.