C++ / Tour
-
const int* vs int* const: how do you read where const goes on a C++ pointer?
`const int*` locks the pointed-to value, whereas `int* const` locks the pointer itself. The dividing line is `*`: `const` to the left of `*` makes the value const, and `const` to the right of `*` makes the pointer const, which is why `const int*` and `int const*` are the same type. Reading a declaration from the variable name leftward keeps the meaning clear. Writing `const T*` or `const T&` on function parameters lets the compiler verify the promise that the function will not modify the argument.
-
What is C++26 std::breakpoint? Using the <debugging> header to stop in the debugger from code
std::breakpoint is a C++26 standard function that asks from within code to pause execution and hand control to the debugger. Previously, developers relied on compiler- or OS-specific facilities such as __debugbreak, __builtin_debugtrap, or asm("int3"), which are now standardized under the <debugging> header. Use std::breakpoint_if_debugging() to stop only when a debugger is attached, and std::is_debugger_present() to check whether the program is running under a debugger. Exact behavior is implementation-defined, and GCC 14.2 in our environment did not include this header yet.
-
What is SIMD? How one instruction processes multiple data and how to check C++ compiler auto-vectorization
Following a Hacker News discussion on accelerating computer vision (FAST) with 128-bit SIMD on the ESP32-S3, this post explains SIMD (Single Instruction, Multiple Data) and how to check C++ compiler auto-vectorization with g++ on a PC using `-O3 -fopt-info-vec-optimized`.
-
static_cast vs reinterpret_cast: how do you choose a C++ cast?
Use `static_cast` for conversions the compiler understands—numeric value conversions, scoped `enum` to integer, restoring `void*` back to its original object pointer type, and pointer or reference conversions within an inheritance hierarchy. Use `reinterpret_cast` for low-level conversions that reinterpret the underlying bits or change how a pointer is viewed—converting between a pointer and `std::uintptr_t`, or between unrelated pointer types. As verified by the compiler errors below, `static_cast` cannot convert `int*` to `double*`, while `reinterpret_cast` cannot convert a `double` value to `int` and cannot remove `const`. For runtime polymorphic type checking use `dynamic_cast`, and to cast away `const` use `const_cast`.
-
What is the C++ "undefined reference" error? Fixing the link error when there is a declaration but no definition
The C++ undefined reference error occurs at link time when compilation succeeds but the linker cannot find a matching definition for a declared symbol. Four cases reproduced with g++ 14.2 and nm output show common causes and fixes.
-
What are std::future and std::promise? Getting a result back from a C++ thread, and how std::async differs
std::future is the standard C++ handle for receiving a one-shot value or exception computed on another thread. This post explains std::promise, std::async, broken_promise, and wait_for with programs verified on g++ 14.2.
-
What is the C++ "multiple definition" error? Why a function defined in a header needs inline
The C++ multiple definition error is a classic link-time failure when a non-inline function body lives in a header included from multiple .cpp files. Using code and linker output reproduced with g++ (Debian 14.2.0-19) 14.2.0 on 2026-10-25 (KST), this post explains One Definition Rule (ODR) violations and fixes with inline, a declaration/definition split, or static/internal linkage.
-
What is C++ lambda capture? The difference between [=] and [&], and when dangling references appear
C++ lambda capture is the syntax that brings outer-scope variables into a lambda by copy ([=]) or by reference ([&]). When a lambda outlives the variable—returned, stored, or passed to another thread—reference capture dangles. This post covers g++ 14.2 examples, catching stack-use-after-return with AddressSanitizer, and [*this] and smart-pointer capture rules.
-
What is a virtual destructor in C++? Why delete through a base pointer needs virtual
A virtual destructor ensures deleting through a base pointer runs the destructor of the object’s real type. Without virtual on the base destructor, the standard calls that undefined behavior. This post covers g++ 14.2 observations, smart pointers, and interview answers.
-
What are C++26 Contracts? Checking function conditions with pre, post and contract_assert
C++26 Contracts let you attach pre and post to a function declaration and check conditions in the body with contract_assert. This post contrasts assert, explains evaluation semantics, and documents GCC 14.2 lack of support versus GCC 16 in the cppreference table, with real g++ output.
-
What is the Rust borrow checker? How it differs from C++ ownership and lifetimes
The Rust borrow checker enforces ownership, references, and lifetimes at compile time. This post walks through E0382, E0502, and E0597 with real rustc and g++ output, and contrasts the model with C++ RAII and AddressSanitizer.
-
What is the "expected unqualified-id before numeric constant" error? How to fix C++ macro name clashes
The expected unqualified-id before numeric constant error appears when a macro such as #define MAX_SIZE 100 expands where a name belongs and leaves a number behind. This post explains the cause and fixes—renaming, constexpr, or #undef—using code and real g++ 14.2.0 compiler output reproduced on 2026-10-21 (KST).
-
What is valgrind? How it differs from ASan when hunting C/C++ memory leaks
valgrind (Memcheck) runs your existing binary without recompilation to catch leaks, uninitialised reads, invalid accesses, and bad frees, but slows execution by roughly 20–30×. When you can recompile, start with AddressSanitizer (~2× slowdown); reach for valgrind when you cannot recompile or need --track-origins=yes and a full leak summary in one run.
-
What is C++ RAII? When to let destructors release resources automatically
C++ RAII (Resource Acquisition Is Initialization, also called SBRM) binds resources that must be acquired before use—heap memory, threads, sockets, files, mutex locks—to object lifetime. Constructors acquire (or throw); destructors release without throwing, in reverse order of acquisition on every exit path. This guide covers lock_guard, smart pointers, custom guards, embedded use, and interview FAQs.
-
What Is C++ explicit? When to Block Implicit Constructor Conversions
C++ explicit stops constructors, conversion functions (since C++11), and deduction guides (since C++17) from taking part in implicit conversions and copy-initialization. A constructor without explicit is a converting constructor, so a call such as f(5) can turn a raw value into an object. Prefer explicit on single-argument constructors, and leave it off only when the conversion is natural, as with std::string s = "abc";.
-
What Is a C++ Compiler Front End? How GCC, Clang, MSVC, and EDG Differ
A C++ compiler front end processes source code through lexing, parsing, and semantic analysis (including template instantiation and `constexpr` evaluation) to produce a hardware-independent intermediate representation (IR or IL). In contrast, the back end takes this intermediate representation and translates it into machine code for the target CPU. This architectural separation underpins major compilers like GCC, Clang, MSVC, and EDG. EDG is particularly distinctive because its front end itself has long been its primary product. On September 30, 2026, EDG's C++ front end source code was made publicly available under The C++ Alliance as its nonprofit home, licensed under the Apache License v2.0 with LLVM Exceptions.
-
What Is C++ Integral Promotion? Why ~true Evaluates to true
Before any arithmetic or bitwise operation runs, integer types smaller than `int` (such as `bool`, `char`, and `short`) are automatically converted into a value-preserving `int` (or `unsigned int`). This is known as integral promotion. As a result, `true` promotes to `int 1`, and flipping its bits with `~` yields `-2` under two's-complement representation; converting `-2` back to `bool` evaluates to `true` because it is nonzero. To negate a boolean, always use `!` instead of `~`.
-
std::vector Reallocation and Iterator Invalidation: Why Crashes Happen After push_back
When the number of elements exceeds its `capacity()`, `std::vector` performs a reallocation: it allocates a new, larger block of memory, moves the existing elements into it, and frees the old block. Once that happens, every iterator, pointer, and reference that pointed into the old buffer becomes dangling, and using it afterward is undefined behavior (UB). If you know the number of elements in advance, calling `reserve()` to pre-allocate capacity is the standard way to avoid reallocation entirely.
-
What Is C++ Insights? How to See the Code Your Compiler Hides (Lambdas, Range-for)
C++ Insights is a Clang-based source-to-source transformation tool that re-expands what the compiler actually does behind your source code back into plain C++. It lets you see which class and `operator()` a lambda turns into, how a range-for loop is expanded into a `begin`/`end` iterator loop, and which constructor gets implicitly called when a struct is copy-initialized — all in the same C++ syntax, not assembly.
-
Copy Constructor vs Move Constructor in C++: Which One Is Called, and When?
The copy constructor vs move constructor question comes down to what gets handed over. A copy constructor (T(const T&)) leaves the source untouched and duplicates everything, while a move constructor (T(T&&)) takes over the source's resources (a heap pointer, for example) and leaves the source in a valid-but-unspecified state. Named lvalues pick the copy constructor; temporaries and objects cast with std::move pick the move constructor — and a common trap is that declaring a destructor alone suppresses the compiler-generated move constructor.
-
std::map vs std::unordered_map: What's the Difference, and When Do You Use Which?
The map vs unordered_map difference comes down to internal structure: std::map is a tree that keeps keys sorted, guaranteeing O(log n) for lookup, insertion, and deletion, while std::unordered_map uses hash buckets for average O(1) but no ordering. Choose map when you need sorting or range search, and unordered_map when you mostly do single-key lookups and order doesn't matter.
-
How to Use ThreadSanitizer to Find C++ Data Races
Build and link with -fsanitize=thread so ThreadSanitizer reports data races at run time. Read Write/Previous write stacks and thread creation sites, and keep AddressSanitizer in a separate build.
-
C++20 Ranges: Composable Views for Filtering and Transforming Sequences
C++20 ranges treats a sequence as a lightweight view so filtering, transforming, and sorting can be composed without copying elements.
-
Using std::jthread and stop_token for Cooperative Thread Cancellation
C++20 std::jthread automatically calls join() on destruction and carries an internal std::stop_source for cooperative cancellation. This note covers auto-join behavior and how to pass and check a stop_token.
-
A Tour of C++ 1.1 — What to grasp first when reading C++
A Tour of C++ §1.1 Introduction. Before memorizing syntax, hold notation, types, memory and computation models, and the mechanisms that build programs.
-
A Tour of C++ 2.6 — Advice: Choosing struct, class, enum, and variant
When built-in types are insufficient in C++, design and choose the appropriate user-defined type to group related data and prevent invalid states. This post summarizes when to use struct, class, enum class, and std::variant from Chapter 2.
-
A Tour of C++ 3.1 — Introduction: Declarations vs Definitions
In C++, a declaration tells the compiler enough to use a name, while a definition provides the actual implementation body. This post introduces the separation of interface and implementation from Chapter 3.
-
A Tour of C++ 3.2 — Separate Compilation: Headers vs C++20 Modules
Traditional #include headers cause repeated parsing and dependency leaks in separate compilation, while C++20 modules solve these overheads through single-time compilation and macro isolation.
-
A Tour of C++ 1.8 — Tests: Conditions, Short-Circuit, and Control Flow
A Tour of C++ §1.8 covers how C++ expresses selection and looping with if, switch, while, and for. This post clarifies truthiness, short-circuit evaluation, if-initialization, switch fall-through, and common control-flow mistakes.
-
A Tour of C++ 2.5 — Unions: Active Members and std::variant
A union lets several members share one block of memory to save space, but the programmer must track which member is currently valid. This post explains union hazards and why std::variant offers a type-safe alternative since C++17.
-
A Tour of C++ 1.10 — Advice: C++ Coding Habits
C++ coding habits are not just new syntax—they are rules for consistently handling comments, initialization, naming, scope, and constants. This post concludes Chapter 1 with practical advice from Bjarne Stroustrup's study notes.
-
A Tour of C++ 1.9 — Mapping to Hardware: Pointers vs References
The core of C++ mapping to hardware is that basic operations translate directly into single machine instructions without extra runtime overhead. This article explains the memory model and the differences between pointers and references.
-
A Tour of C++ 2.1–2.2 — User-Defined Types and struct Vector
Built-in types are low-level tools that mirror hardware capabilities; user-defined types layer abstraction on top. This post covers the first step—grouping data with struct—and introduces the Tour's Vector example.
-
A Tour of C++ 2.3 — Classes: Enforcing Invariants with Constructors
A C++ class separates the public interface from private implementation and enforces invariants immediately upon object creation using a constructor. This article covers why struct Vector was insufficient and how a class fixes it.
-
A Tour of C++ 1.8 — Tests: Conditions, Short-Circuit, and Control Flow
A Tour of C++ §1.8 covers how C++ expresses selection and looping with if, switch, while, and for. This post clarifies truthiness, short-circuit evaluation, if-initialization, switch fall-through, and common control-flow mistakes.
-
Formatting Output with C++ std::format
In C++20, std::format takes a format string, substitutes the supplied arguments, and returns formatted text. A safe, extensible alternative to printf and a complement to iostreams.