Warn about class member self-initialization

c++, compiler-options, gcc, initialization, warnings

Solution

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

Problem

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++?

Original source