Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid/warn self initialization of C++ members

Tags:

c++

gcc

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.

like image 957
user1255770 Avatar asked Sep 05 '13 11:09

user1255770


2 Answers

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.

like image 144
Mike Seymour Avatar answered Sep 28 '22 19:09

Mike Seymour


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]
like image 30
trojanfoe Avatar answered Sep 28 '22 18:09

trojanfoe