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/ # Expressions Based on *C++ Primer, 5th ed.* Chapter 4 (Expressions). ## lvalues and rvalues Every [expression]({{< relref "/programming/c/syntax-basics.md#expression-vs-statement" >}}) in C++ is characterized by two independent properties: its **type** and its **value category**. ### Core Distinction: Expression vs. Variable vs. Object - **Expression:** Possesses both a **type** (reference stripped) and a **value category** (lvalue, xvalue, prvalue). Value categories are strictly properties of *expressions*, never of variables. - **Variable:** Possesses only a **declared type** (e.g., `int`, `int&`, `int&&`); a variable itself has no value category. When a variable's name appears in code as an expression, that *expression* is evaluated as an lvalue (e.g., given `int &&rr = 10;`, variable `rr` has declared type `int&&`, while the expression `rr` has type `int` and value category lvalue). - **Object vs. Variable:** - **Object:** A region of storage in memory holding a value. - **Variable:** A **named object** or a **named reference** introduced by a declaration. | Entity | Is Object? (Occupies Storage) | Is Variable? (Has Name) | Note | | :--- | :---: | :---: | :--- | | `x` in `int x = 10;` | ✅ | ✅ | Named object in memory | | `r` in `int &r = x;` | ❌ | ✅ | Named reference (alias; unlike a pointer, `r` has no separate address of its own distinct from `x`, though used as an expression `r` designates `x` and is an lvalue with identity `&r == &x`) | | `10 + 20` (temporary) | ✅ | ❌ | Unnamed temporary object | ### Two Axes of Value Categories - **Identity:** Does the expression have an identifiable memory address (can we test whether two expressions designate the same entity with `&`)? - **Movable:** Can the object's resources be safely stolen or moved because it is expiring? ### Value Categories Matrix (C++11) | | Non-movable | Movable | | :--- | :--- | :--- | | **Has Identity** | **lvalue** | **xvalue** (*eXpiring* value) | | **No Identity** | *(does not exist)* | **prvalue** (*pure* rvalue) | ``` Value Category / \ glvalue rvalue / \ / \ lvalue xvalue prvalue ``` ### The 5 Value Categories #### 1. Primary Categories - **lvalue (Left Value):** Has identity and cannot be moved from. Represents persistent objects or functions in memory. - eg. Named variables (`x`), dereference expressions (`*ptr`), prefix increment/decrement (`++i`), function calls returning lvalue references (`std::cout << 1`). - **prvalue (Pure Rvalue):** Has no identity and can be moved from. Represents transient values computed on the fly. In C++17, a prvalue is an evaluation recipe that initializes an object. - eg. Numeric/boolean literals (`42`, `true`, excluding string literals), arithmetic expressions (`a + b`), function calls returning by value (`GetPoint()`). - **xvalue (eXpiring Value):** Has identity and can be moved from. Designates an object nearing the end of its lifetime whose resources can be safely repurposed. - eg. Cast to rvalue reference (`std::move(x)` / `static_cast(x)`), accessing a non-static member of an rvalue (`GetPoint().x`). #### 2. Composite Categories - **glvalue (Generalized lvalue):** lvalue + xvalue. Any expression whose evaluation determines the identity of an object or function. - **rvalue:** prvalue + xvalue. Any expression eligible for move semantics. ### Example ```cpp std::string a = "hello"; std::string b = "world"; a; // lvalue: has persistent identity, cannot be moved from a + b; // prvalue: transient computed value without persistent identity std::move(a); // xvalue: designates existing object 'a', but marked movable ``` ### `decltype` Two-Step Deduction Rules and Expressions `decltype(...)` evaluates its operand using a **two-step rule (Rule 1 → Rule 2)**: * **[Rule 1] Unparenthesized Variable / Member Name (`decltype(i)`, `decltype(obj.x)`):** - Does **not** evaluate the expression's value category (lvalue/rvalue); instead, it directly returns the exact **declared type** of that variable (`int i;` → `int`). * **[Rule 2] All Other Expressions (`decltype(*p)`, `decltype((i))`, `decltype(i + 1)`):** - Deduces the type based on the expression's **Value Category**: - **lvalue expression:** yields an lvalue reference (`T&`). - **xvalue expression:** yields an rvalue reference (`T&&`). - **prvalue expression:** yields the non-reference value type (`T`). - **Parenthesized Expression `(expr)` Rule:** Parentheses never alter the value category of the inner expression `expr`. Adding parentheses around `i` in `decltype((i))` simply disqualifies it from **Rule 1** (bare variable name) so it falls through to **Rule 2**, where its lvalue category yields `int&`. By contrast, `decltype((42))` is a prvalue and yields `int`. ```cpp int i = 42; int *p = &i; decltype(i) r1 = 0; // int ([Rule 1] bare variable name -> declared type) decltype((i)) r2 = i; // int& ([Rule 2] parenthesized (i) is an lvalue expression -> T&) decltype(*p) r3 = i; // int& ([Rule 2] *p is an lvalue expression -> T&) decltype(&p) r4 = &p; // int** ([Rule 2] &p is a prvalue expression -> T) decltype(std::move(i)) r5 = std::move(i); // int&& ([Rule 2] std::move(i) is an xvalue expression -> T&&) ``` ### Reference Binding (`T&`, `const T&`, `T&&`) and Move Semantics For reference binding rules across lvalue and rvalue categories (why `int &r = 42` is forbidden, temporary lifetime extension with `const T&`, and `T&&` rvalue references), why a named `T&&` variable is an lvalue expression, and how `std::move` and `std::forward` work, see **[Copy Elision & Move Semantics]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md" >}})**. --- ## Operators and Value Categories For differences in operator return categories between C and C++, see [lvalues and rvalues in C vs. C++]({{< relref "/programming/c/c-vs-cpp.md#lvalues-and-rvalues-in-c-vs-c" >}}). ### 1. Assignment Operator (`=`) - The LHS (left-hand operand) must be a **modifiable lvalue**. - The result of an assignment is its LHS as an **lvalue**. - The type of the result matches the type of the LHS. - Assignment is **right-associative** (groups from right to left). ```cpp int a, b; a = b = 10; // Parsed as a = (b = 10): valid in both C and C++ ((b = 10) sits on the RHS, where an rvalue is fine) (a = b) = 42; // Compile error in C ((a = b) is an rvalue and cannot be the LHS), valid in C++ ((a = b) yields a as an lvalue) ``` > In C, the result of an assignment is an rvalue (the value transferred), whereas in C++ it is an lvalue. Chained assignment `a = b = 10;` still works in C because right-associativity groups it as `a = (b = 10);`, placing `(b = 10)` on the **RHS**. By contrast, `(a = b) = 42;` places the assignment result on the **LHS**, which fails in C and succeeds only in C++. ### 2. Increment and Decrement (`++`, `--`) - **Prefix (`++i`, `--i`):** Increments/decrements the operand and returns the object itself as an **lvalue** (`CLASS&`). - **Postfix (`i++`, `i--`):** Returns a copy of the object's original value as an **rvalue** (`CLASS`), then modifies the operand. - For `CLASS& operator++()` vs. `CLASS operator++(int)` overloading details, see [Overloaded Operations: Prefix vs. Postfix]({{< relref "/programming/cpp/primer/operator-overloading.md#2-implementation-idioms-by-operator" >}}). ```cpp int i = 0; ++i = 5; // Valid: prefix yields an lvalue // i++ = 5; // Error: postfix yields an rvalue ``` > Prefer prefix operators in C++ unless the original value is explicitly required. Prefix avoids creating temporary copies for complex types and iterators. ### 3. Member Access (`->`, `.`) - **Arrow operator (`->`):** Requires a pointer operand and always yields an **lvalue** (`ptr->m` is equivalent to `(*ptr).m`). - **Dot operator (`.`):** - Yields an **lvalue** if the object owning the member is an lvalue. - Yields an **rvalue** (xvalue) if the object owning the member is an rvalue. ```cpp struct Point { int x, y; }; Point p{1, 2}; Point GetPoint() { return {3, 4}; } p.x; // lvalue (p is an lvalue) GetPoint().x; // xvalue (member of an rvalue temporary) ``` ### 4. Conditional Operator (`?:`) The conditional operator (`cond ? expr1 : expr2`) evaluates to: - An **lvalue** if both `expr1` and `expr2` are lvalues of the same type (or convert to a common lvalue type). - An **rvalue** otherwise. ```cpp int a = 10, b = 20; ((a < b) ? a : b) = 30; // Valid in C++: yields an lvalue (assigns 30 to a) int x = (true ? 1 : 2); // Yields an rvalue ``` > In C, `?:` always yields an rvalue regardless of operand categories.