§The Annotated C++ StandardC++ 标准注疏 中文

Idioms & Patterns

Common C++ idioms and design patterns, and the language rules they rest on.

RAII and scope guardsTying a resource's lifetime to an object's lifetime: which language rules guarantee that destructors run, how to write a move-only resource handle, using unique_ptr deleters and scope guards and what they cost, locks and threads in the standard library, lifetimes across coroutine suspension, and the cases RAII doesn't cover plus common traps.draftRAIIscope guarddestructorslifetimePimpl and the compilation firewallHiding a class's data members behind a pointer to an incomplete type: the recompilation cascades and shared-library ABI problems it solves, where the special members of a unique_ptr implementation must be defined, const propagation, copying and the empty state after a move, C++26's std::indirect, fast pimpl, and its run-time costs and alternatives.draftpimplcompilation firewallABIincomplete typesSingletons and static initialization orderWhy the initialization and destruction order of global objects across translation units is unreliable; which part of the problem the Meyers singleton, constinit, never-destroyed singletons, nifty counters and inline variables each solve; the cost of the guard check; multiple copies of a singleton in shared libraries; and replacing singletons with dependency injection.draftsingletonstatic initializationSIOFconstinitNon-virtual interface and template methodA public non-virtual function does the checking, locking and logging, then calls a private virtual function for the customizable step. Why private virtual functions can be overridden, why access checks and default arguments both use the static type, why the template method cannot run during construction, why final does not necessarily devirtualize here, and how the standard library itself uses this structure.draftidiomvirtual functionsaccess controltemplate methodCRTP and static polymorphismA derived class passes itself as the template argument of its base (class D : public Base<D>): why this compiles, why static_cast<D&>(*this) is safe, how it differs from virtual functions in code generation and object size, where the standard library uses it, the common traps, and which of its uses C++23's explicit object parameters replace.draftCRTPstatic polymorphismtemplatesdeducing thisMixinsBuilding a class out of several unrelated, reusable small classes through inheritance: CRTP-style mixins parameterized on the derived class and layered mixins parameterized on the base class, how constructors pass through the layers, resolving name clashes, size under the empty base optimization, the overloaded idiom, and which mixins deducing this can replace.draftmixininheritanceCRTPinherited constructorsPolicy-based designSplitting a class template's behavior into several orthogonal dimensions, each provided by a template argument (a policy): how policies get into the host class, how they achieve zero overhead, policies in the standard library, constraining policies with concepts, and combinatorial explosion, type incompatibility and compile-time costs.draftidiomdesign patternstemplatespoliciesFive ways to write a strategyExtracting the replaceable step of an algorithm and implementing the same pricing strategy with a virtual interface, std::function and its successors, a template parameter, a function pointer and std::variant; comparing ownership, run-time replaceability, size, allocation, levels of indirection, inlining and error messages, ending with a selection table.draftdesign patternsstrategyvirtual functionsstd::functionVisitors: double dispatch and std::visitAdding operations to a fixed set of types without changing them: how the classic visitor gets double dispatch from two virtual calls, the two directions of the expression problem, the acyclic visitor, the closed-set approach with std::variant and std::visit, exhaustiveness checking, multiple dispatch and how it is implemented, the indirection a recursive variant needs, and the measured costs of both approaches.draftvisitordouble dispatchvariantvisitType erasure from the ground upRun-time polymorphism without a common base class and with value semantics: hand-building a Drawable step by step from an internal virtual interface, adding copying, moving, a small buffer and a hand-written vtable, explaining the rules of placement new, launder, lifetimes and noexcept moves, then looking at what each type-erasing type in the standard library erases and what it costs.drafttype erasurepolymorphismvalue semanticssmall-object optimizationObservers and callback lifetimesA subject notifies a set of observers; the hard part is not the notification but which side dies first: what raw pointer lists, unsubscribing in the destructor, weak_ptr and RAII connection objects each protect against, how reentrancy during notification and callbacks invoked under a lock go wrong, and dangling captured this in callbacks.draftdesign patternsobservercallbackslifetimeFactories and self-registrationCreating objects by name or ID without the caller knowing the concrete type: factory functions returning unique_ptr, clone and covariant return types, a registry mapping names to creator functions, self-registration through static objects in each translation unit and why it breaks with static libraries, deferred initialization, initialization order and threads, compile-time registries, and abstract factories.draftdesign patternsfactoryregistrystatic initializationTag dispatch: from overloading to conceptsFour ways to choose an implementation at compile time from the properties of a type: iterator category tags, enable_if, if constexpr and constrained overloads; which language rule each relies on, what their error messages look like, how much extra compile time they cost, and why the standard library uses empty tag types instead of bool parameters everywhere.drafttag dispatchSFINAEif constexprconceptsExpression templatesEvaluating a + b + c in one loop without temporary vectors: operators return lightweight objects that record the structure of the computation, and evaluation happens element by element on assignment. Constraining the operators with concepts, dealing with auto dangling and aliasing, and comparing with valarray, ranges' zip_transform, std::linalg and Eigen.draftexpression templatesoperator overloadinglazy evaluationdanglingStrong types and phantom typesUsing a class that wraps a single value to split quantities with the same representation but different meanings into different types: why typedef can't do it, the Strong<T, Tag> template and phantom tags, adding operations as needed, the conditions for zero overhead and the assembly, enum class as a strong integer, chrono::duration, std::byte and align_val_t in the standard library, unit conversions, and traps around implicit conversions, hashing and formatting.draftstrong typesphantom typesenum classchronoPasskey and attorney-clientA friend gets every private member at once. Passkey restricts a single public function to chosen callers, attorney-client forwards only selected private members; plus the gaps that `{}` aggregate initialization, make_shared, explicit instantiation and static reflection leave in access control.draftaccess controlfriendpasskeyattorney-clientNamed parameters and buildersC++ has no named arguments. How to make a call like open("f", true, false, 4096) readable: enums instead of bool parameters, option aggregates with designated initializers, method chains returning *this by reference, ref-qualifiers and explicit object parameters for temporary builders, and a few traps of default arguments.draftidiomdesignated initializersaggregatesbuilder