After having been bitten by doing something like:
struct Person {
std::string first_name;
std::string last_name;
Person(const std::string &first_name_, const std::string &last_name_) :
first_name(first_name_),
last_name(last_name)
{}
};
Where the initializer last_name(last_name)
should obviously be last_name(last_name_)
are there any way I can make gcc warn about such an error (is there ever any use case of initializing a member using itself ?)
Or any suggestion on a better naming convention in cases where constructor arguments are similar to the fields.
I avoid the issue by using the same name for the arguments as the members they initialise. The lookup rules specify that the name refers to the argument, when used in a member initialiser.
There is scope for subtle errors if the constructor is too complicated; but no problem if you're simply initialising members in the initialiser list.
Otherwise, GCC will give a warning about using an uninitialised value with sensible warning settings like -Wall
(or perhaps -Wextra
), or more specifically -Wuninitialized
. I think there might also be a -Winit-self
or similar, if you want to be even more specific.
Yes; -Wuninitialized
and -Winit-self
:
$ g++ -Wuninitialized -Winit-self -c init.cpp
init.cpp: In constructor 'Person::Person(const string&, const string&)':
init.cpp:7:3: warning: 'Person::last_name' is initialized with itself [-Wuninitialized]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With