Avoid / prevent self initialization of C ++ members

After a bite, 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) {} }; 

If the last_name(last_name) initializer should obviously be last_name(last_name_) is there a way I can get gcc to warn me of such an error (is there ever some kind of element initialization that I use myself?)

Or any suggestion for a better naming convention in cases where the constructor arguments are similar to fields.

+6
source share
2 answers

I avoid the problem by using the same name for the arguments as members that they initialize. Search rules indicate that a name refers to an argument when used in a member initializer.

Subtle errors are likely if the constructor is too complex; but not a problem if you simply initialize the participants in the initializer list.

Otherwise, GCC will give a warning about using an uninitialized value with reasonable warning settings, such as -Wall (or, possibly, -Wextra ), or, more specifically, -Wuninitialized . I think it could also be -Winit-self or similar if you want to be more specific.

+9
source

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] 
+7
source

Source: https://habr.com/ru/post/953235/


All Articles