Advanced C++ Patterns
Apply advanced C++ design patterns and idioms — RAII, CRTP, type erasure, policy-based design, and modern C++ idioms.
50 min•By Priygop Team•Last updated: Feb 2026
Modern C++ Idioms
- RAII (Resource Acquisition Is Initialization): Tie resource lifetime to object lifetime — constructor acquires, destructor releases. No manual cleanup. Smart pointers, lock_guard, fstream
- CRTP (Curiously Recurring Template Pattern): class Derived : public Base<Derived> — static polymorphism without virtual function overhead. Mixins, compile-time interfaces
- Type Erasure: Hide concrete types behind a common interface without inheritance — std::function, std::any implement this. Enables heterogeneous containers
- Policy-Based Design: Template parameters that define behavior — template<class SortPolicy, class StoragePolicy> class Container. Compile-time customization without runtime cost
- PIMPL (Pointer to Implementation): Hide implementation in a separate class — reduces compilation dependencies. Changed implementation doesn't recompile dependents
- Rule of Zero/Five: Prefer Rule of Zero (no custom destructor/copy/move — let smart pointers handle it). If you need one of the five, implement all five
Move Semantics Deep Dive
- Rvalue References (&&): Bind to temporary objects — enable 'stealing' resources instead of copying. std::vector<int> v = createLargeVector(); — moves, doesn't copy
- std::move: Cast to rvalue reference — doesn't move anything, just enables moving. After std::move, the object is in a valid but unspecified state
- Perfect Forwarding: template<typename T> void wrapper(T&& arg) { inner(std::forward<T>(arg)); } — preserves value category (lvalue/rvalue) through function calls
- Move-Only Types: std::unique_ptr can't be copied, only moved — enforces single ownership at compile time. Use for resources that shouldn't be shared
- Copy Elision (NRVO): Compiler eliminates copies — MyClass create() { MyClass obj; return obj; } constructs directly in the caller's space. Guaranteed in C++17