user1255770
user1255770

Reputation: 1642

Avoid/warn self initialization of C++ members

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.

Upvotes: 6

Views: 1862

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

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]

Upvotes: 7

Mike Seymour
Mike Seymour

Reputation: 254501

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.

Upvotes: 9

Related Questions