wiki:cpp-most-vexing-parse
Table of Contents
C++ Most vexing parse
Most vexing parse is the surprising rule that in contexts ambiguous between a declaration and a temporary, the compiler interprets it as a declaration. For example, Widget w(Widget()); declares w as a function returning Widget, not a Widget object initialized with a temporary.
Use brace initialization Widget w{}; to avoid ambiguity with function declarations.
Example
This example shows the most vexing parse trap and how brace initialization avoids it.
// compile: g++ -o vexing vexing.cpp // run: ./vexing // description: most vexing parse: function declaration vs. temporary #include <iostream> class Widget { public: Widget() { std::cout << "Widget constructed\n"; } void print() { std::cout << "Widget method\n"; } }; int main() { // Most vexing parse: declares w as function returning Widget // Widget w(Widget()); // These avoid the trap: Widget w1{}; // brace init: constructs w1 Widget w2{Widget()}; // brace init with temp Widget w3 = Widget(); // assignment init w1.print(); return 0; }
wiki/cpp-most-vexing-parse.md · Last modified: by 127.0.0.1
