Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Most Vexing Parse & In-Class Initializer This page covers the exact conditions that trigger the **Most Vexing Parse** when initializing objects with `()` in C++, contrasts it with the rule that **prohibits `()` altogether for in-class member initializers**, and explains the **`std::initializer_list` constructor hijacking pitfall** when using braces `{}` as a workaround. --- ## 1. What Is the Most Vexing Parse? Coined by Scott Meyers in *Effective STL* (Item 6), the **Most Vexing Parse** refers to a counterintuitive consequence of C++'s syntactic disambiguation rule where **code intended to instantiate an object using `()` is instead parsed by the compiler as a function declaration**. > **C++ Disambiguation Rule:** > *"Any construct that could possibly be interpreted as a **function declaration** must be interpreted as a **function declaration**, rather than an object definition."* ### Why Is It Hard to Spot? - Although C/C++ does not allow **defining** a nested function (`{ ... }`) inside another function, C backward compatibility allows **declaring a function prototype inside a function body** (a block-scope function forward declaration). - Consequently, on the line where you write `Widget w();` inside a function, the compiler sees a completely valid function forward declaration and **emits no compile error on that line** (modern compilers emit a `-Wvexing-parse` warning). Instead, compile or linker errors appear only later when you try to use `w` as an object (`w.run();`). --- ## 2. Three Classic Patterns of the Most Vexing Parse Here are the three most common cases where using `()` in local scope (such as inside `main()`) is unintentionally parsed as a function declaration: ### Pattern 1: Default-Constructing with Empty Parentheses (`Widget w();`) ```cpp class Widget { public: Widget() = default; void run() {} }; void example1() { // ❌ Developer intent: Default-construct a local Widget object named w // ⚠️ Actual parse: "Declare a function named w taking no parameters (void) and returning Widget" Widget w(); // w.run(); // Compile error: w is a function (Widget ()), not a Widget object! } ``` ### Pattern 2: Passing an Unnamed Temporary as an Argument (`TagHolder th(std::vector());`) This frequently bites developers when calling an `explicit` constructor with an empty container or temporary object. ```cpp class TagHolder { public: explicit TagHolder(std::vector input) {} }; void example2() { // ❌ Developer intent: Pass an empty temporary vector to TagHolder's constructor // ⚠️ Actual parse: "Declare a function named th that takes a function pointer // (std::vector (*)()) and returns a TagHolder"! TagHolder th(std::vector()); } ``` - **Why is it parsed as a function declaration?** In C/C++ function declarations, parameter names can be omitted, and a function type `std::vector()` written in a parameter position automatically decays into a function pointer `std::vector (*)()`. Thus, `std::vector()` inside the parentheses is parsed not as an **"expression constructing a temporary object"**, but as an **"unnamed function-pointer parameter type"**, that is, as a function declaration. ### Pattern 3: Passing a Temporary Construction Expression (`Bar b(Foo(x));`) ```cpp struct Foo { explicit Foo(int x) {} }; struct Bar { explicit Bar(Foo f) {} }; void example3() { int x = 10; // ❌ Developer intent: Construct a temporary Foo(x) from variable x and pass it to Bar's constructor // ⚠️ Actual parse: "Declare a function named b taking a parameter x of type Foo // (with redundant parentheses around the parameter name: 'Foo (x)') and returning Bar"! Bar b(Foo(x)); } ``` - **Why is it parsed as a function declaration?** C/C++ syntax allows redundant parentheses around variable and parameter names (`int (x);` is identical to `int x;`). Therefore, the compiler parses `Foo(x)` not as a constructor call with argument `x`, but as **a parameter declaration of type `Foo` named `x` (`Foo (x)`)**. --- ## 3. When Do Parentheses `()` Construct an Object vs. Declare a Function? The single deciding criterion is: **"Can the contents inside `(...)` be syntactically read as a function parameter declaration list?"** | Code in Local Scope | Contents of `(...)` | Compiler Interpretation | Reason | | :--- | :--- | :---: | :--- | | `Widget w(10);`
`Widget w("hi");` | **Literal value** | ✅ **Object Creation** | `10` or `"hi"` cannot be a type name, so a function declaration is impossible | | `int x = 10;`
`Widget w(x);` | **Existing variable name alone** | ✅ **Object Creation** | `x` is a variable name, not a type name, so a function declaration is impossible | | `Widget w();` | **Empty `()`** | ⚠️ **Function Declaration**
*(Most Vexing Parse)* | Valid as a zero-parameter function declaration `Widget w(void);` | | `Bar b(Foo());` | **`TYPE()` form** | ⚠️ **Function Declaration**
*(Most Vexing Parse)* | `Foo()` is valid as an unnamed function-pointer parameter `Foo (*)()` | | `Bar b(Foo(x));` | **`TYPE(x)` form** | ⚠️ **Function Declaration**
*(Most Vexing Parse)* | `Foo(x)` is valid as a parenthesized parameter declaration `Foo (x)` | --- ## 4. Common Confusion: Local Function Scope vs. Inside a Class Definition (`class { ... }`) How `()` behaves in these two scopes must be clearly distinguished: ### 1. Inside a Function Body (Local Scope): Where the Most Vexing Parse Happens - Inside a function body, direct initialization with `()` is **normally allowed** (`std::vector v(10);` ✅). - Only when the syntax inside `()` happens to match a valid parameter list (`Widget w();` or `Bar b(Foo());`) does it silently turn into a **function declaration (Most Vexing Parse)** without a compiler error. ### 2. Inside a Class Definition (In-Class Initializer): Where `()` Initialization Is Banned Outright - A class body (`class MyClass { ... };`) is a space where **member function declarations** (`RETURN_TYPE FUNCTION(...);`) are listed. - Furthermore, inside a class, members can reference other members declared later in the class body. If `int a(b);` were allowed as an in-class member initializer, a compiler reading top-to-bottom could not tell whether `b` is **a type name not yet seen (making `a` a member function declaration)** or **another member variable declared further down (making `a` a data member initializer)**. - To **eliminate this ambiguity completely**, C++11 **prohibits `()` for in-class member initializers altogether as a hard compile error**, even when passing a literal like `int c(10);` (only `=` or braces `{}` are permitted; see [Classes: In-Class Initializer]({{< relref "/programming/cpp/primer/classes.md#3-in-class-initializer" >}})). ```cpp // [A] Inside a Class Definition (In-Class Initializer): () member initialization is banned outright! class MyClass { int a = 10; // ✅ = initialization allowed int b{10}; // ✅ Brace {} initialization allowed // int c(10); // ❌ Compile error! () is banned for in-class initializers even with literal 10! int d(); // ⚠️ Compiles, but declares a MEMBER FUNCTION d(), not a data member! // Caution: Initializing a type that has an initializer_list constructor (like std::vector) with size 10 in-class std::vector v1{10}; // ⚠️ Creates a 1-element vector containing {10}, NOT a 10-element vector! std::vector v2 = std::vector(10); // ✅ Use '= TYPE(...)' to create a 10-element vector in-class! }; // [B] Inside a Function Body (Local Scope): () initialization is allowed, but ambiguous forms trigger Most Vexing Parse! void myFunc() { std::vector v1(10); // ✅ Valid object creation (10-element vector, 10 is a value, not a type) std::vector v2(); // ⚠️ Most Vexing Parse: declares a function, not a vector object! } ``` | Comparison | Inside a Function Body (Local Scope) | Inside a Class Definition (`class { ... }`) | | :--- | :--- | :--- | | **Is `()` initialization generally allowed?** | ✅ **Yes** | ❌ **No (Banned outright; use `=` or `{}` only)** | | **`int c(10);`** | ✅ Creates an `int` initialized to `10` | ❌ **Compile Error** (`expected parameter declarator`) | | **`int d();`** | ⚠️ Parsed as a function declaration (**Most Vexing Parse**) | ⚠️ Parsed as a **member function declaration** | --- ## 5. Solutions and the Brace `{}` Pitfall (`std::initializer_list` Hijacking) ### 1. Brace Initialization (`{}`): Watch Out for `std::initializer_list`! Because function parameter lists in C++ can never be enclosed in curly braces `{}`, using `{}` completely prevents a declaration from being parsed as a function. **However, `{}` is not a blind drop-in replacement for `()`: its behavior depends critically on whether the braces are empty `{}` or non-empty `{a, b}`!** #### (1) Empty Braces `{}` for Default Construction: **100% Safe** By C++ standard rule, even if a class defines a `std::initializer_list` constructor, **empty braces `{}` ALWAYS invoke the default constructor**, never the `initializer_list` constructor. ```cpp // Fix Pattern 1: Default construction with empty {} (Always safe) Widget w{}; // Fix Pattern 2: Passing an empty container temporary (Empty {} always calls default constructor) TagHolder th1(std::vector{}); // Inner temporary uses empty {} -> Guaranteed default constructor! TagHolder th2{std::vector()}; // Outer TagHolder uses {} (no initializer_list ctor) -> Fixed! ``` #### (2) Non-Empty Braces `{a, b}`: **Beware `std::initializer_list` Constructor Hijacking!** If a class has a constructor taking `std::initializer_list` (most notably standard containers like `std::vector` and `std::string`), **putting arguments inside `{...}` causes the compiler to strongly prefer the `std::initializer_list` constructor over regular constructors**: ```cpp // std::vector has both vector(size_type count, const int& val) and vector(std::initializer_list)! std::vector v1(10); // () calls vector(size_type): 10 elements, all 0 ([0, 0, ..., 0]) std::vector v2{10}; // {} calls vector(initializer_list): 1 element with value 10 ([10])! std::vector v3(10, 20); // () calls vector(size_type, val): 10 elements, all 20 ([20, 20, ..., 20]) std::vector v4{10, 20}; // {} calls vector(initializer_list): 2 elements, 10 and 20 ([10, 20])! ``` - Therefore, `{}` is completely safe for **empty braces `{}` (default construction)** or **classes without a `std::initializer_list` constructor** (`Widget`, `TagHolder`, `Bar`), - But when calling a **non-`initializer_list` constructor on a type like `std::vector`** (such as specifying initial size), you should use Solution 2 or Solution 3 below instead of `{}`! ### 2. Use `= TYPE(...)` or `auto` with Explicit Right-Hand Construction (C++17+) Writing `auto name = TYPE(...);` or `TYPE member = TYPE(...);` (in-class) can never be parsed as a function declaration, and allows you to keep using `()` on the right-hand side, **avoiding both the Most Vexing Parse and `std::initializer_list` hijacking**. Since C++17 **Guaranteed Copy Elision** constructs the prvalue directly in place with zero copies or moves, there is zero performance overhead (see [Copy Elision & Move Semantics]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md" >}})). ```cpp auto w = Widget(); auto th = TagHolder(std::vector()); auto v = std::vector(10); // Creates a 10-element vector without initializer_list hijacking! ``` ### 3. Wrap the Argument in Extra Parentheses `(( ... ))` (Pre-C++11 Legacy Idiom) Because a parameter type declaration in a function signature cannot be surrounded by an outer pair of parentheses, wrapping the argument in `(( ... ))` forces the compiler to parse it as an expression without using `{}`. ```cpp Bar b((Foo())); // Extra parentheses ((...)) force expression parsing Bar b2((Foo(x))); // Also parsed as object creation ```