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_keeperof classTimeKeeper, initialized with an anonymous instance of classTime. - A function declaration for a function
time_keeperthat returns an object of typeTimeKeeperand has a single (unnamed) parameter, whose type is a function taking no input and returningTimeobject.
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{}};