Most Vexing Parsing
Most vexing parsing is a counterintuitive form of syntactic ambiguity resolution in the C++ programming language. Sometimes C++ grammer(or compiler) can not distinguish between the creation of an object parameter
and specification of a function type
. [1]
A Simple Example
int x();
This line of code may look like a function declaration, but it's actually a declaration of a function pointer named x
that takes no arguments and returns an integer. To declare a function that takes no arguments and returns an integer, the correct syntax would be:
int x(void);
Example from WiKi
struct Timer {};
struct TimeKeeper {
explict TimeKeeper(Timer t);
int get_time();
};
int main() {
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}
In this line:
TimeKeeper time_keeper(Timer());
is ambiguous, since it could be interpreted either as:
- A variable definition for variable
time_keeper
of classTimeKeeper
, initialized with an anonymous instance of classTime
. - A function declaration for a function
time_keeper
that returns an object of typeTimeKeeper
and has a single (unnamed) parameter, whose type is a function taking no input and returningTime
object.
Solutions
Since C++11 introduce uniform initialization that allows limited omission of the type name entirely.
TimeKeeper time_keeper(Timer{});
TimeKeeper time_keeper{Timer()};
TimeKeeper time_keeper{Timer{}};