Skip to content

示例

161 个可独立运行的示例。每个文件开头都写了自己的编译命令;这里链接的是仓库里的真实源码。

示例 演示内容
abstract-factory-demo.cpp Demonstrates the Abstract Factory Pattern: create families of related
active-record-demo.cpp Demonstrates the Active Record Pattern: each object knows how to persist
adapter-pattern-demo.cpp Demonstrates Adapter Pattern: VlcPlayer + Mp3Player adapted to MediaPlayer interface.
auto-decltype.cpp Demonstrates auto, decltype, and decltype(auto) in C++.
balking-demo.cpp Demonstrates the Balking Pattern: an operation only proceeds when the
bridge-pattern-demo.cpp Demonstrates Bridge Pattern: Abstraction with Implementation hierarchy decoupled.
builder-demo.cpp Demonstrates the Builder Pattern: step-by-step construction of a complex
chain-of-responsibility-demo.cpp Demonstrates Chain of Responsibility: Auth -> Logging -> Validation -> Processing.
chrono-calendar.cpp Demonstrates the C++20 chrono calendar: year/month/day arithmetic,
command-pattern-demo.cpp Demonstrates Command Pattern with TextEditor, InsertCommand, CommandHistory (undo/redo).
composite-demo.cpp Demonstrates the Composite Pattern: treat individual objects and
connection-pool-concurrency.cpp Demonstrates ConnectionPool concurrent access and thread safety.
const-vs-non-const.cpp Demonstrates the performance difference between const and non-const methods.
constexpr.cpp Demonstrates constexpr variables, functions, and if constexpr.
copy-elision.cpp Demonstrates copy elision and prvalue materialization in C++.
copy_on_write_example.cpp Demonstrates Copy-on-Write (COW) pattern in C++.
coroutine-basics.cpp Demonstrates C++20 coroutine fundamentals.
cpp20-concepts-complete.cpp Demonstrates C++20 concepts, requires clauses and constrained templates.
cpp20-concepts.cpp Demonstrates C++20 concepts for template constraints.
cpp20-consteval.cpp Demonstrates C++20 consteval and constinit.
cpp20-coroutines-complete.cpp Demonstrates C++20 coroutines: generators and tasks.
cpp20-coroutines.cpp Demonstrates C++20 coroutine basics.
cpp20-format.cpp Demonstrates C++20 std::format for string formatting.
cpp20-ranges.cpp Demonstrates C++20 ranges library.
cpp20-span.cpp Demonstrates C++20 std::span for non-owning views.
cpp23-features-complete.cpp Demonstrates the C++23 features used across this repository.
cpp23-ranges-views.cpp Demonstrates C++23 additions to : views::zip, views::enumerate,
cpp23-small-features.cpp Demonstrates smaller C++23 library features: std::string::contains,
cqrs-pattern-demo.cpp Demonstrates CQRS Pattern: CommandBus/QueryBus separated, AccountService with in-memory store.
crtp-basics.cpp Demonstrates the Curiously Recurring Template Pattern for static polymorphism.
decorator-pattern-demo.cpp Demonstrates Decorator Pattern: FileDataSource with Encryption + Compression + Logging.
deducing-this.cpp Demonstrates C++26 explicit object parameter ("deducing this"): one
delegation-demo.cpp Demonstrates the Delegation Pattern: an object forwards part of its work
double-dispatch-demo.cpp Demonstrates Double Dispatch: one operation that depends on the runtime types of two operands.
event-sourcing-demo.cpp Demonstrates Event Sourcing: EventStore, Account aggregate, replay from events.
facade-demo.cpp Demonstrates the Facade Pattern: a simplified interface over a set of
factory-pattern-demo.cpp Demonstrates the Factory Method Pattern with auto-registration.
flyweight-pattern-demo.cpp Demonstrates Flyweight Pattern: Shared fonts in text editor.
fold-expressions.cpp Demonstrates C++17 fold expressions for summing, multiplying and concatenating.
forwarding-references.cpp Demonstrates forwarding references and perfect forwarding in C++.
if-consteval.cpp Demonstrates C++23 if consteval: branch on whether evaluation is happening
inplace-vector.cpp Demonstrates std::inplace_vector (C++26): a vector with inline storage -
interpreter-pattern-demo.cpp Demonstrates Interpreter Pattern: Expression tree with Number/Add/Multiply/Variable.
iterator-pattern-demo.cpp Demonstrates the iterator design pattern: an iterator interface, aggregates that create one, and the client code that never knows the difference.
lambda-expressions.cpp Demonstrates lambda expressions in C++11/14/17.
lvalue-rvalue-references.cpp Demonstrates lvalue and rvalue references in C++.
mediator-pattern-demo.cpp Demonstrates Mediator Pattern: ChatRoom mediates between Users.
memento-pattern-demo.cpp Demonstrates Memento Pattern: Editor + History for undo/redo.
memory-pool-demo.cpp Demonstrates three ways of handing out memory: a free list pool, an arena that never gives anything back, and a slab allocator with one free list per size.
move-semantics-advanced.cpp Demonstrates advanced move semantics: NRVO, move vs copy, and common pitfalls.
move-semantics-example.cpp Demonstrates move semantics and how copying differs from moving.
mvc-pattern-demo.cpp Demonstrates MVC Pattern with TodoModel / TodoView / TodoController.
noexcept-move.cpp Demonstrates noexcept and move operations in C++.
nttp-class-type.cpp Demonstrates C++20 non-type template parameters of class type and
null-object-pattern-demo.cpp Demonstrates the Null Object Pattern: a null object answers every call with a do-nothing default, so the client never checks for null.
observer-pattern-demo.cpp Demonstrates Subject-Observer with Logger and Counter observers.
ownership-and-lifetime.cpp Demonstrates different ownership semantics in C++17 and their impact on object lifetime.
perfect-forwarding.cpp Demonstrates forwarding references and perfect forwarding.
pimpl-idiom.cpp Demonstrates PImpl (Pointer to Implementation) idiom for ABI stability.
pitfall-broken-double-checked-locking.cpp Demonstrates broken double-checked locking and the safe replacements.
pitfall-const-correctness-pitfalls.cpp Demonstrates const correctness pitfalls: temporary lifetime, mutable state, and casting away const.
pitfall-const-object-move-trap.cpp Demonstrates that std::move applied to a const object silently copies instead of moving.
pitfall-dangling-lambda-captures.cpp Demonstrates dangling lambda captures and the ownership patterns that prevent them.
pitfall-dangling-pointer.cpp Demonstrates dangling-pointer scenarios (use-after-free) and the ownership patterns that prevent them.
pitfall-dangling-reference.cpp Demonstrates dangling reference pitfalls and their fixes.
pitfall-dangling-string-view.cpp Demonstrates dangling std::string_view pitfalls and the safe owning alternatives.
pitfall-data-race.cpp Demonstrates data races and the std::atomic / std::mutex fixes.
pitfall-deadlock.cpp Demonstrates a lock-ordering deadlock and the deadlock-free std::scoped_lock fix.
pitfall-deleting-through-non-virtual-base.cpp Demonstrates why deleting an object through a base pointer needs a virtual destructor.
pitfall-double-free.cpp Demonstrates double-free bugs and the ownership patterns that prevent them.
pitfall-fold-expression-errors.cpp Demonstrates fold expression mistakes: empty packs, wrong parentheses, and the fixes.
pitfall-implicit-conversions.cpp Demonstrates implicit conversions in C++ and the bugs they silently cause.
pitfall-iterator-invalidation-pitfalls.cpp Demonstrates iterator invalidation pitfalls and the safe patterns.
pitfall-iterator-invalidation.cpp Demonstrates iterator invalidation pitfalls and their fixes.
pitfall-livelock.cpp Demonstrates a polite-yield livelock and the fixes: random backoff and a single owner.
pitfall-macro-pitfalls.cpp Demonstrates macro pitfalls (precedence, double evaluation, statement macros) and their fixes.
pitfall-memory-fragmentation.cpp Demonstrates heap fragmentation from interleaved frees and the arena/pool fix.
pitfall-memory-leak.cpp Demonstrates memory leaks caused by manual ownership and the RAII fix.
pitfall-memory-order-pitfalls.cpp Demonstrates why a relaxed atomic handshake is not a synchronisation point and how acquire/release fixes it.
pitfall-moving-from-const-object.cpp Demonstrates that std::move on a const object copies, and shows the sink-API patterns that really move.
pitfall-narrowing-conversions.cpp Demonstrates narrowing conversions in brace, parenthesis and copy initialization.
pitfall-object-lifetime-and-destruction-order-pitfalls.cpp Demonstrates object lifetime rules: destruction order, dangling access and shared_ptr cycles.
pitfall-object-slicing.cpp Demonstrates object slicing pitfalls and their fixes.
pitfall-priority-inversion.cpp Demonstrates priority inversion and its fixes: priority inheritance, short critical sections and lock-free design.
pitfall-sfinae-misuse.cpp Demonstrates that a constraint in the function body is a hard error, while the same constraint in the signature is a soft SFINAE failure.
pitfall-signed-integer-overflow-assumptions.cpp Demonstrates that signed overflow is undefined behaviour and shows checked arithmetic patterns.
pitfall-stack-overflow.cpp Demonstrates stack overflow from unbounded recursion and the iterative fix.
pitfall-static-initialization-order-fiasco.cpp Demonstrates the static initialization order fiasco and the fixes: Meyers' singleton, constexpr and constinit.
pitfall-template-deduction-pitfalls.cpp Demonstrates forwarding-reference deduction, reference collapsing, non-deduced contexts and CTAD.
pitfall-template-specialization-pitfalls.cpp Demonstrates template specialization mistakes: partial specialization of functions, std templates, and silent misses.
pitfall-the-myth-of-thread-safety.cpp Demonstrates why const, atomics and per-object locks are not enough on their own.
pitfall-thread-leak.cpp Demonstrates thread leaks (a joinable thread destroyed, a detached thread) and the RAII fixes.
pitfall-thread-safety-composition-fallacy.cpp Demonstrates why thread-safe operations do not compose into a thread-safe whole.
pitfall-throwing-from-destructor.cpp Demonstrates why destructors must be non-throwing and how to report cleanup failures safely.
pitfall-uninitialized-members.cpp Demonstrates uninitialized member variables and the habits that prevent them.
pitfall-use-after-move.cpp Demonstrates use-after-move pitfalls and the safe alternatives.
prototype-demo.cpp Demonstrates the Prototype Pattern: clone existing objects instead of
proxy-demo.cpp Demonstrates the Proxy Pattern: a surrogate controlling access to a
raii-and-exception-safety.cpp Demonstrates RAII pattern and exception safety in C++.
range-based-for.cpp Demonstrates range-based for loops with various containers.
reference-binding-rules-demo.cpp Demonstrates the rules that decide which reference binds to which expression: the binding matrix, reference collapsing, and the lifetime of a temporary.
repository-pattern-demo.cpp Demonstrates Repository Pattern with User entity and in-memory repository.
rule-of-zero-three-five.cpp Demonstrates Rule of Zero, Three, and Five in C++.
service-locator-demo.cpp Demonstrates the Service Locator Pattern: a central registry that
sfinae-type-traits.cpp Demonstrates SFINAE-based type traits and custom detection idioms.
simd-vectorization.cpp Demonstrates a hand written vectorized loop and the scalar tail beside it.
singleton-pattern-demo.cpp Demonstrates Meyers' Singleton and thread-safe Logger/Config singletons.
smart-pointer-shared.cpp Demonstrates std::shared_ptr for shared ownership.
smart-pointer-unique.cpp Demonstrates std::unique_ptr for exclusive ownership.
smart-pointers-ownership.cpp Demonstrates unique_ptr, shared_ptr, weak_ptr, and ownership patterns.
spaceship-operator.cpp Demonstrates C++20 three-way comparison (operator<=>): defaulted
specification-pattern-demo.cpp Demonstrates Specification Pattern with and/or/not composition.
state-machine-demo.cpp Demonstrates State Machine Pattern: Order lifecycle with explicit transitions.
std-any.cpp Demonstrates std::any for type-erased containers.
std-apply-invoke.cpp Demonstrates std::apply and std::invoke for calling generic callables.
std-bit-cpp20.cpp Demonstrates the C++20 library: popcount, bit_width and bit utilities.
std-chrono-advanced.cpp Demonstrates advanced std::chrono: durations, clocks and time points.
std-chrono-format.cpp Demonstrates formatting std::chrono durations and time points with std::format.
std-chrono-literals.cpp Demonstrates the C++20 chrono literals, such as 100ms and 2s.
std-chrono.cpp Demonstrates C++17 chrono library for time manipulation.
std-clamp.cpp Demonstrates std::clamp for restricting a value to a range.
std-expected.cpp Demonstrates std::expected for returning either a value or an error.
std-filesystem-advanced.cpp Demonstrates advanced std::filesystem: recursion, permissions and symlinks.
std-filesystem-cpp20.cpp Demonstrates std::filesystem for paths, directories and iteration.
std-filesystem.cpp Demonstrates C++17 filesystem library.
std-flat-map.cpp Demonstrates the C++23 std::flat_map and std::flat_set.
std-format.cpp Demonstrates std::format string formatting and format specifications.
std-function.cpp Demonstrates std::function for function objects and callbacks.
std-generator.cpp Demonstrates C++23 std::generator: a coroutine-based lazy sequence without
std-jthread.cpp Demonstrates std::jthread, with automatic joining and stop tokens.
std-latch-barrier.cpp Demonstrates std::latch and std::barrier for coordinating threads.
std-mdspan.cpp Demonstrates the C++23 std::mdspan multidimensional view.
std-optional-advanced.cpp Demonstrates advanced std::optional use: chaining, value_or and monadic calls.
std-optional.cpp Demonstrates std::optional usage and patterns.
std-print-complete.cpp Demonstrates the C++23 std::print and std::println output functions.
std-print-cpp23.cpp Demonstrates the C++23 std::print and std::println output functions.
std-random.cpp Demonstrates C++17 random number generation.
std-ranges-advanced.cpp Demonstrates advanced std::ranges: views, adaptors and algorithms.
std-source-location.cpp Demonstrates std::source_location for compile-time source information.
std-span-complete.cpp Demonstrates std::span: views over contiguous sequences.
std-string-view-advanced.cpp Demonstrates advanced std::string_view: trimming, splitting and lifetime rules.
std-string-view.cpp Demonstrates std::string_view for non-owning string references.
std-tuple.cpp Demonstrates std::tuple for returning multiple values.
std-variant-advanced.cpp Demonstrates advanced std::variant use: visitation, get_if and monadic calls.
std-variant.cpp Demonstrates std::variant for type-safe unions.
strategy-pattern-demo.cpp Demonstrates Strategy Pattern with BubbleSort, QuickSort, InsertionSort.
structured-bindings.cpp Demonstrates structured bindings (C++17) with pairs, tuples, arrays, and structs.
task-scheduler-error-handling.cpp Demonstrates TaskScheduler error handling: cancellation, exception safety,
template-basics.cpp Demonstrates function templates, class templates, and template specialization.
template-instantiation.cpp Demonstrates template instantiation and two-phase lookup in C++.
template-method-demo.cpp Demonstrates the Template Method Pattern: a base class defines the
testing-patterns.cpp Demonstrates mock objects, test fixtures and parameterized tests with a small test harness.
type-object-demo.cpp Demonstrates the Type Object Pattern: represent "types" as data objects
undefined-behavior.cpp Demonstrates common undefined behavior scenarios and how to avoid them.
unit-of-work-demo.cpp Demonstrates the Unit of Work Pattern: track all changes to a set of
value-categories.cpp Demonstrates lvalue, rvalue, prvalue, xvalue, and glvalue.
views-chunk-split.cpp Demonstrates C++23 views::chunk and views::split: batch and tokenize
virtual-dispatch-and-slicing.cpp Demonstrates virtual dispatch, object slicing, and polymorphism.
virtual-dispatch-example.cpp Demonstrates virtual dispatch, polymorphism, and object model in C++.
visitor-pattern-demo.cpp Demonstrates Visitor Pattern: double dispatch for Shapes.
web-server-benchmark.cpp Real HTTP benchmark for the web_server project.