Warn about class member self-initialization
Asked Answered
A

1

6

Have a look at this piece of C++ code:

class Foo
{
    int a;

    public: Foo(int b): a(a) {}
};

Obviously, the developer meant to initialize a with b rather than a itself, and this is a pretty hard to spot error.

Clang++ will warn about this possible mistake while GCC won't, even with additional warnings enabled:

$ clang++ -c init.cpp 
init.cpp:5:27: warning: field is uninitialized when used here [-Wuninitialized]
    public: Foo(int b): a(a) {}
                        ^

$ g++ -Wall -Wuninitialized -Winit-self -c init.cpp 
$

Is there any chance of enabling the same output for g++?

Aid answered 19/8, 2012 at 11:15 Comment(0)
H
8

Use a newer gcc :-) Seems to work fine for me:

stieber@gatekeeper:~$ g++ -Wall -Wuninitialized -Winit-self -c Test.cpp
Test.cpp: In constructor ‘Foo::Foo(int)’:
Test.cpp:5:9: warning: ‘Foo::a’ is initialized with itself [-Wuninitialized]

stieber@gatekeeper:~$ gcc --version
gcc (Debian 4.7.1-2) 4.7.1
Haunch answered 19/8, 2012 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.