最让人头疼的歧义most vexing parse

The most vexing parse is a specific form of syntactic ambiguity resolution in the C++ programming language.

class Timer {
public:
Timer();
};

class TimeKeeper {
public:
TimeKeeper(const Timer& t);

int get_time();
};

int main() {
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}

The line TimeKeeper time_keeper(Timer()); is ambiguous, since it could be interpreted either as

  1. a variable definition for variable time_keeper of class TimeKeeper, initialized with an anonymous instance of class Timer or
  2. a function declaration for a function time_keeper which returns an object of type TimeKeeper and has a single (unnamed) parameter which is a function returning type Timer (and taking no input).

Most programmers expect the first, but the C++ standard requires it to be interpreted as the second. One way to force the compiler to consider this as a variable definition is to add an extra pair of parentheses:TimeKeeper time_keeper( (Timer()) );

Using the new uniform initialization syntax introduced in C++11 solves this issue (and many more headaches related to initialization styles in C++). The problematic code is then unambiguous when braces are used:

TimeKeeper time_keeper{Timer{}};