6

Lets have this code:

#include <iostream>
#include <simd/simd.h>
class X {
public:
    X(int a) : x{a} {} // <-- only x is initialized, y is not

    int x;
    int y;
    simd_double3 d;
};

int main(int argc, const char * argv[]) {
    X x(1);
    X* xx = new X(2);
    std::cout<<x.x<<" "<<x.y<<" "<<x.d.x; // <-- y and x.d are used, but not initialized
    std::cout<<xx->x<<" "<<xx->y<<"END\n";
    return 0;
}

I want to emit warning that y in X is not initialized. -Wall, -Wmissing-field-initializers seems to do nothing. It compiles without warnings. This sample code produces this output: 1 0 6.95323e-310 So even if y is initialized to 0(which is not, because clang analysis marks it as uninitialized), clearly simd_double3 is not initialized to 0.

Also clang analysis mark x.y as uninitialized. (1st function call argument is an uninitialized value)

Also, when creating X on heap in release mode, content of x.y is garbage. Second line prints: 2 -1094795586, y is clearly not initialized.

Juraj Antas
  • 3,059
  • 27
  • 37

1 Answers1

5

I check all warnings with clang 8 (last release version) command line:
clang -O2 -Wall -Wextra -Weverything
Check: https://godbolt.org/z/kKp-N5
Clang hasn't any warnings for uninitialized variables into classes and structs. But using clang-tidy with check cppcoreguidelines-pro-type-member-init may be helpful to you.
https://releases.llvm.org/8.0.0/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-pro-type-member-init.html

V. Bobylev
  • 66
  • 3
  • I guess you are right: Correct answer is: clang does not have warning for uninitialized variables. This sucks, I was burned with this many times, and I believe I am not alone.. clang-tidy is check that can be easily fooled and often reports false positives. – Juraj Antas Jun 05 '19 at 11:21
  • to be more clear no warning for uninitialized variables inside classes and structures. It does warn you for using local uninitialized variable. – Juraj Antas Jun 13 '19 at 12:45