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/ # Smart Pointers Summary based on *C++ Primer, 5th ed.* Chapter 12 (Dynamic Memory and Smart Pointers). ## 1. Why Smart Pointers Exist (RAII and Ownership) - **Stack vs. Heap Lifetimes:** Stack local variables automatically invoke their destructor (`~Class()`) when leaving scope (`{ ... }`), whereas heap memory allocated via `new` is NOT automatically freed when a raw pointer (`T*`) goes out of scope, leading to memory leaks. - **[RAII (Resource Acquisition Is Initialization)]({{< relref "/programming/cpp/raii.md" >}}):** By wrapping a raw pointer (`T*`) inside a **stack-allocated wrapper class** whose **destructor (`~SmartPtr()`) automatically calls `delete ptr;`**, heap memory is deterministically freed when the wrapper leaves scope. - **The Copy / Double-Free Problem and Ownership Models:** If two smart pointers pointed to the same heap address and both called `delete` in their destructors, a fatal **Double Free** crash would occur. To solve this, C++11 `` provides three smart pointers with distinct ownership semantics: | Smart Pointer | Ownership Model | Copyable? | `*ptr` / `ptr->` Dereference | Key Characteristics & Use Case | | :--- | :--- | :---: | :---: | :--- | | **`std::unique_ptr`** | **Exclusive Ownership** — 1:1 | ❌ `std::move` only | ✅ | Zero overhead with the same size and speed as `T*`; the default choice for dynamic memory. | | **`std::shared_ptr`** | **Shared Ownership** — N:1 | ✅ updates `use_count` | ✅ | Calls `delete` only when the strong reference count `use_count` in the Control Block reaches 0. | | **`std::weak_ptr`** | **Non-Owning** — Observer | ✅ `use_count` unchanged | ❌ `.lock()` required | Observes a `shared_ptr`-managed object without incrementing `use_count`, breaking **circular reference memory leaks**. | --- ## 2. `std::unique_ptr`: Exclusive Ownership and `std::make_unique` Because only one `unique_ptr` can own a given object at a time, its copy constructor and copy-assignment operator are deleted (`= delete`). - **Creation:** Prefer **`std::make_unique`** (introduced in C++14) over raw `new`. - **Ownership Transfer:** Copying is prohibited; ownership can only be transferred via **`std::move`**. ```cpp #include // Recommended: Create via std::make_unique instead of raw new auto up1 = std::make_unique("hello"); // auto up2 = up1; // ❌ Compile error: cannot copy exclusive ownership auto up2 = std::move(up1); // ✅ Valid: transfers ownership from up1 to up2 (up1 becomes nullptr) // Dereference using * and -> just like a raw pointer *up2 = "world"; size_t len = up2->size(); // Supports dynamic arrays and automatically calls delete[] upon destruction auto arr = std::make_unique(10); // Length 10, all elements 0 (equivalent to new int[10]()) ``` ### How `unique_ptr` Works Under the Hood (`get`, `release`, `reset`) `std::unique_ptr` is not magic, it is simply a **thin RAII wrapper class holding a single raw pointer member variable (`T* ptr_`)**. Looking at its simplified implementation makes what `get()`, `release()`, and `reset()` actually do immediately obvious: ```cpp template class unique_ptr { private: T* ptr_ = nullptr; // The sole member variable holding the heap address public: // Constructor: takes a raw pointer and stores it in ptr_ (acquires ownership) explicit unique_ptr(T* p = nullptr) noexcept : ptr_(p) {} // Destructor: automatically deletes ptr_ when leaving scope // Note: In C++, delete nullptr; is guaranteed to be a safe no-op ~unique_ptr() noexcept { delete ptr_; } // 1. get(): simply returns the stored address without modifying ptr_ T* get() const noexcept { return ptr_; } // 2. release(): sets ptr_ = nullptr without calling delete, and returns the old address // -> When ~unique_ptr() later runs, it executes delete nullptr; which is a no-op T* release() noexcept { T* old_ptr = ptr_; ptr_ = nullptr; return old_ptr; } // 3. reset(): immediately deletes old_ptr and replaces ptr_ with new_ptr // -> Calling up.reset() with no arguments sets ptr_ = nullptr and destroys the old object early void reset(T* new_ptr = nullptr) noexcept { T* old_ptr = ptr_; ptr_ = new_ptr; delete old_ptr; } }; ``` - **Why Is the `unique_ptr(T* p)` Constructor `noexcept`? — Separation from `make_unique`:** - The `unique_ptr` constructor itself never allocates heap memory; heap allocation happens beforehand inside **`new` or the `std::make_unique` helper function**. For `Args&&...` and `...` pack expansion syntax, see [Templates: Variadic Templates]({{< relref "/programming/cpp/primer/templates.md#3-variadic-templates-args-and-emplace_back" >}}): ```cpp template unique_ptr make_unique(Args&&... args) { // NOT noexcept: inner new can throw std::bad_alloc T* p = new T(std::forward(args)...); // Heap allocation completes before entering unique_ptr's constructor return unique_ptr(p); // Passes only the already-allocated address p } ``` - Any `std::bad_alloc` is thrown while evaluating `new` before `unique_ptr(T* p)` is ever entered. Inside `unique_ptr(T* p)`, **0 heap allocations** occur — it merely copies the pointer `p` into `ptr_`, guaranteeing `noexcept`. - **When to use each method:** 1. **`.get()` — Borrowing the address:** Use when passing the pointer to a function `void Print(const Foo* f)` that only reads or inspects the object without taking ownership: `Print(up.get())`. 2. **`.release()` — Detaching ownership without deleting the heap object:** Use when you need `unique_ptr` to stop auto-deleting the object so you can hand the raw pointer off to a legacy C API or another wrapper that will delete it. 3. **`.reset(...)` — Immediately deleting or replacing the heap object:** Call `up.reset()` to destroy the heap object early before the scope ends, or `up.reset(new Foo())` to delete the existing object and take ownership of a new one. ### Three Ownership Rules When Interacting with Raw Pointers `T*` Based on when `ptr_` is deleted above, whenever you pass or receive a raw pointer `T*`, track **who holds ownership — the responsibility to call `delete`**: | Method | Deletes Existing Heap Object? & Behavior | Ownership Transfer | Mandatory Caller Rule | | :--- | :--- | :---: | :--- | | **`.reset(RAW_PTR)`**
**`unique_ptr(RAW_PTR)`** | Immediately calls `delete` on any previously managed object, then acquires ownership of `RAW_PTR` | Caller → `unique_ptr` | **Immediately give up ownership** of `RAW_PTR`. Never manually `delete` it or pass it to another smart pointer, or a **Double Free** occurs. | | **`.get()`** | Does **not** call `delete` — `unique_ptr` retains ownership and returns the internal `T*` address for observation only | None | **Never `delete` the returned pointer or wrap it in another smart pointer**, or a **Double Free** occurs. | | **`.release()`** | Does **not** call `delete` — sets the internal pointer to `nullptr` to relinquish ownership and returns the live `T*` address | `unique_ptr` → Caller | **Always take ownership** of the returned pointer. Pass it to another smart pointer or manually `delete` it, or a **memory leak** occurs. | ```cpp // 1. Constructor / .reset(): ownership moves into unique_ptr -> never delete raw outside int* raw = new int(10); std::unique_ptr up(raw); // delete raw; // ❌ Forbidden: causes Double Free when up is destroyed // 2. .get(): borrows the raw address without transferring ownership -> never delete or re-wrap int* borrowed = up.get(); // delete borrowed; // ❌ Forbidden: Double Free // std::unique_ptr bad(borrowed); // ❌ Forbidden: two unique_ptrs now own the same address // 3. .release(): up becomes nullptr without deleting -> caller MUST take ownership int* released = up.release(); // up is now nullptr and ~unique_ptr() will NOT delete it delete released; // ✅ Safe: must manually delete or transfer to another owner to prevent a leak ``` --- ## 3. `std::shared_ptr`: Control Block and `std::make_shared` Because multiple `shared_ptr` instances across independent scopes must share the exact same `use_count` in real time, the reference count cannot live inside an individual stack variable — it must reside in a separate heap-allocated **Control Block**. Accordingly, a `shared_ptr` internally holds two pointers: the object pointer (`T*`) and a **Control Block pointer**. When the last `shared_ptr` is destroyed and `use_count` reaches `0`, the managed object is automatically deleted. - **Why `shared_ptr(T* p)` Is NOT `noexcept` Unlike `unique_ptr(T* p)`:** - When constructing `shared_ptr sp(new int(42));`, `new int(42)` allocates only the `int` beforehand; **inside `shared_ptr(T* p)`'s constructor, a second heap allocation (`new ControlBlock`) must be performed**. - Because allocating the Control Block can throw `std::bad_alloc`, `shared_ptr(T* p)` cannot be `noexcept` (if Control Block allocation fails, the constructor catches the exception, calls `delete p;` to prevent leaking `p`, and rethrows). - Conversely, **`std::make_shared`** allocates a single contiguous block holding both `T` and the `ControlBlock` in **1 heap allocation**, cutting allocation overhead in half and improving cache locality. | Call Target | Heap Allocations **Inside** the Function | Total Heap Allocations | `noexcept`? | | :--- | :--- | :---: | :---: | | **`unique_ptr(p)` constructor** | **0** — copies already-allocated address `p` | 1 (outer `new`) | ✅ | | **`std::make_unique`** | **1** (`new T`) | 1 | ❌ can throw `bad_alloc` | | **`shared_ptr(p)` constructor** | **1** (`new ControlBlock`) | **2** (outer `new` + Control Block) | ❌ can throw `bad_alloc` | | **`std::make_shared`** | **1** (combined `T` + `ControlBlock`) | **1** | ❌ can throw `bad_alloc` | ```cpp // Recommended: Prefer std::make_shared over raw new { auto sp1 = std::make_shared(10, '9'); // Single allocation for object + Control Block, use_count == 1 { auto sp2 = sp1; // Shares existing Control Block pointer and increments use_count: 1 -> 2 — 0 allocations, noexcept std::cout << *sp2 << " (" << sp2->size() << ")\n"; // Dereference via * and -> } // sp2 leaves scope, decrementing use_count: 2 -> 1 — not 0 yet, so object remains alive } // sp1 leaves scope, decrementing use_count: 1 -> 0 and automatically freeing heap memory! ``` --- ## 4. `std::weak_ptr`: Breaking Circular References and `lock()` ### 1. How Circular Reference Memory Leaks Happen If two objects reference each other using `shared_ptr`, their reference counts remain stuck at `1` even after all external variables go out of scope, leaking both objects forever: ```cpp struct Node { std::shared_ptr next; std::shared_ptr prev; // Cause of leak: both directions use strong references (shared_ptr)! }; void circular_leak_example() { auto spA = std::make_shared(); // 1. spA points to Node A -> [Node A use_count = 1] auto spB = std::make_shared(); // 2. spB points to Node B -> [Node B use_count = 1] spA->next = spB; // 3. Both spB and spA->next point to Node B -> [Node B use_count = 2] spB->prev = spA; // 4. Both spA and spB->prev point to Node A -> [Node A use_count = 2] } // 5. Function ends: spA and spB are destroyed, but both nodes remain at use_count == 1 (memory leak!) ``` Why neither node is freed when the function exits (Step 5): - **Node A's `use_count` (`2 → 1`):** Local variable `spA` is destroyed, but `spB->prev` still holds a strong reference to Node A. - **Node B's `use_count` (`2 → 1`):** Local variable `spB` is destroyed, but `spA->next` still holds a strong reference to Node B. - Because neither reference count reaches `0`, both objects are leaked on the heap forever. ### 2. Breaking the Cycle with `std::weak_ptr` and `lock()` Changing one direction (e.g., `prev`) to `std::weak_ptr` **does not increment `use_count`**, allowing both nodes' `use_count` to reach `0` cleanly when `spA` and `spB` leave scope. Because a `weak_ptr` does not own the object, the target may have already been destroyed. Therefore, **`weak_ptr` cannot be directly dereferenced (`*wp` and `wp->` do not exist)**. You must call **`wp.lock()`** to check whether the object still exists and obtain a temporary `shared_ptr`: - **If the target object is still alive (`use_count >= 1`):** `wp.lock()` returns a valid `std::shared_ptr` and **increments `use_count` by `+1`** for the duration of the `if` block, guaranteeing the object cannot be destroyed while in use. - **If the target object has already been destroyed (`use_count == 0`):** `wp.lock()` returns an **empty `std::shared_ptr` (`nullptr`)**, which evaluates to `false` in the `if` condition. ```cpp auto orig = std::make_shared(42); // use_count == 1 std::weak_ptr wp(orig); // Observes without incrementing count (use_count == 1) if (auto sp = wp.lock()) { // 1. Target is alive: returns valid shared_ptr 'sp' and increments [use_count == 2] inside this block! // 2. Dereference (*, ->) using the returned shared_ptr 'sp' *sp = 100; } // 3. Leaving the if block destroys 'sp', decrementing [use_count == 1] orig.reset(); // Releases ownership -> [use_count == 0], int object is destroyed! if (auto sp = wp.lock()) { // Target is already destroyed: wp.lock() returns empty shared_ptr (nullptr), skipping this block } ```