Juraj Antas
Juraj Antas

Reputation: 2712

C++ enable warning for uninitialized variables in classes

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.

Upvotes: 10

Views: 3212

Answers (1)

V. Bobylev
V. Bobylev

Reputation: 86

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

Upvotes: 7

Related Questions