Most Vexing Parse
The term “most vexing parse” was first used by Scott Meyers in his 2001 book Effective STL.
1. Introduction
The “most vexing parse” is a famous ambiguity in C++ syntax. It occurs when the compiler interprets a statement as function declaration instead of an object construction.
1 |
|
Some compilers provide warnings that can help catch potential most vexing parse issues using -Wvexing-parse
. The above code will generate compile warnings if this option is enabled.
1 | <source>:8:16: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse] |
C++ grammar allows declarations to look very similar to expressions. When the compiler encounters MyClass obj();
, it prioritizes interpreting it as a declaration (because declarations are more fundamental in the language’s parsing rules) rather than an expression creating an object.
Another common example when using std::vector
1 | std::vector<int> v(10, 20); // Correct: Creates a vector with 10 elements of value 20 |
2. How to fix?
1 | MyClass obj{}; // Use uniform initialization with braces (C++11 and later): |
References
Most Vexing Parse