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/ # Namespaces Summary based on *C++ Primer, 5th ed.* Section 18.2 (Namespaces) and Modern C++ (C++17) best practices. ## 1. Purpose and Basic Syntax Namespaces partition the global scope into distinct logical scopes to prevent name collisions (**Global Namespace Pollution**) when combining multiple libraries in large-scale programs. - **No Trailing Semicolon:** Unlike class definitions (`class Foo { ... };`), a namespace block does **not** end with a semicolon (`;`). - **Discontiguous Definitions:** A namespace can be split across multiple files (`.h` and `.cc`) or blocks. Reopening an existing namespace adds declarations to it rather than creating a new one. - **Scope Operator (`::`):** Members are accessed via `ns::name`. Writing a leading `::name` with no prefix explicitly refers to `name` in the **global namespace**. - **Nested Namespaces:** Namespaces can be nested inside one another; since **C++17**, nested namespaces can be written concisely as `namespace a::b::c { ... }`. ```cpp int version = 1; // Global namespace (::version) // Classic nested declaration (pre-C++17) namespace my_lib { namespace internal { int version = 2; } } // No semicolon needed // C++17 nested namespace shorthand (equivalent) namespace my_lib::net { class Client { public: int GetGlobalVersion() const { return ::version; // Explicitly accesses global ::version (1) } }; } // namespace my_lib::net ``` --- ## 2. Unnamed (Anonymous) Namespaces and Internal Linkage A block declared as `namespace { ... }` without a name is an **unnamed (anonymous) namespace**. - **Internal Linkage:** Every variable, function, class, or type alias declared inside an anonymous namespace has **internal linkage**, visible **only within the current `.cc` translation unit** and invisible to the linker from any other file. Internally, the compiler treats `namespace { ... }` as defining a uniquely named hidden namespace followed immediately by `using namespace ;`, so within the same translation unit its members are accessed directly outside the braces without hiding or qualification. - **Comparison with File-Scope `static`:** [File-scope `static`]({{< relref "/programming/c/static.md" >}}) inherited from C (`static int x;`, `static void f();`) also gives internal linkage, **but `static` can only be applied to variables and functions, never to `class`, `struct`, or `using` declarations**. An anonymous namespace hides everything inside it uniformly, making it the standard idiom in C++ implementation files. | Feature | File-Scope `static` | Anonymous Namespace (`namespace { ... }`) | | :--- | :--- | :--- | | **Applicable Entities** | Variables and free functions only | Variables, functions, **`class` / `struct`, `enum`, `using` aliases** | | **Linkage** | Internal Linkage | Internal Linkage (C++11+) | | **C++ Recommendation** | Legacy compatibility | **Preferred standard for file-private code in `.cc` files** | ### Warning: Never Put an Anonymous Namespace in a Header File (`.h`) Because `#include "foo.h"` textually copies the header into every `.cc` translation unit that includes it, placing `namespace { ... }` in a header gives **each translation unit its own distinct private copy**, causing three serious bugs: 1. **Code & Data Bloat:** Including the header in 100 `.cc` files duplicates every table and helper function 100 times in the final binary. 2. **Split State Bugs:** A mutable or static variable inside `namespace { ... }` in a header has separate storage in `a.cc` and `b.cc`, silently breaking shared state assumptions. 3. **One Definition Rule (ODR) Violation (Undefined Behavior):** Any `inline` function or class template in that header that references an entity from the anonymous namespace binds to a *different* entity in every `.cc` file, violating C++'s **One Definition Rule (ODR)**. > **Sharing Constants Safely in Headers:** Use **`inline constexpr`** (C++17+) inside a named namespace so every translation unit shares **one single entity**. ```cpp // config.h (Recommended: C++17 inline constexpr) namespace app { inline constexpr int kMaxRetries = 3; inline constexpr std::string_view kDefaultHost = "localhost"; } // namespace app ``` --- ## 3. Namespace Aliases, `using` Declarations, and `using` Directives C++ provides three mechanisms to avoid repeating long namespace prefixes: | Construct | Example | Behavior & Scope | Allowed in `.h` Headers? | | :--- | :--- | :--- | :---: | | **namespace alias** | `namespace fs = std::filesystem;` | Introduces a short synonym for a long namespace path. | Caution (keep inside local/internal scope) | | **`using` declaration** | `using std::string;` | Brings **one specific symbol** into the current scope. Collisions are caught immediately at compile time. | Only inside function/class scope | | **`using` directive** | `using namespace std;` | Makes **every name** in that namespace visible at once, risking silent overload hijacking or name clashes. | **Strictly Forbidden** | > **Why `using namespace ...;` Is Forbidden in Headers:** Writing `using namespace std;` at file scope in a header forces every symbol in `std` into the global scope of **every `.cc` file that transitively includes that header**, causing fragile name collisions across unrelated files. --- ## 4. Argument-Dependent Lookup (ADL) Ordinarily, functions inside a namespace require explicit qualification (`ns::func(x)`). However, **when an unqualified function call passes arguments of class, struct, or enum type, the compiler automatically searches the namespaces where those argument types are defined**. This rule is called **Argument-Dependent Lookup (ADL)** (or **Koenig Lookup**). ### Two Essential Real-World Uses of ADL 1. **Operator Overloading (`std::cout << s`):** Writing `std::cout << s` invokes the non-member `operator<<(std::cout, s)`. Even without writing `std::operator<<(std::cout, s)`, ADL inspects the parameter types (`std::ostream` and `std::string`), sees they belong to `namespace std`, and automatically finds `std::operator<<`. 2. **The Two-Step `swap` Idiom in Generic Code (`using std::swap; swap(a, b);`):** Calling `std::swap(a, b)` with explicit qualification forces the compiler to ignore any specialized `swap` defined in `T`'s own namespace. Writing an **unqualified** `swap(a, b)` after `using std::swap;` lets ADL pick `T`'s custom fast `swap` if one exists, falling back cleanly to `std::swap` otherwise: ```cpp #include namespace custom { struct Buffer { int *data; }; // Fast custom swap in Buffer's own namespace void swap(Buffer &lhs, Buffer &rhs) noexcept { std::swap(lhs.data, rhs.data); } } // namespace custom template void DoWork(T &a, T &b) { using std::swap; // Step 1: Make std::swap available as fallback swap(a, b); // Step 2: Call without std:: qualifier // -> If T is custom::Buffer, ADL selects custom::swap // -> If T is int, falls back to std::swap } ```