| name | modern-cpp |
| description | Expert Modern C++ programming skill covering C++11 through C++26. Use when the user needs C++ code, asks about C++ features, best practices, optimization, debugging, templates, move semantics, smart pointers, STL containers/algorithms, CMake, software design patterns, or any C++ programming topic. Triggers on mentions of C++, modern C++, C++ standard features, C++ performance, C++ compile errors, or when writing/refactoring C++ code. |
Modern C++ Programming Skill
Comprehensive C++ expertise covering C++11/14/17/20/23/26 based on Federico Busato's "Modern C++ Programming" course (25 lectures, 1600+ slides).
Skill Architecture
This skill uses progressive disclosure. Read reference files as needed:
| Domain | Reference File | Topics |
|---|
| Foundation | reference/01_foundation.md | Ch 1-2: History, Philosophy, Setup, Compilation |
| Type System | reference/02_type_system.md | Ch 3-4: Types, Operators, Integral/Floating-point |
| Core Concepts | reference/03_core_concepts.md | Ch 5-7: Entities, Control Flow, Memory, Functions, Lambdas |
| OOP | reference/04_oop.md | Ch 8-9: Classes, Polymorphism, Operator Overloading |
| Templates | reference/05_templates.md | Ch 10-11: Templates, SFINAE, Concepts, Meta-programming |
| Translation Units | reference/06_translation_units.md | Ch 12-13: Linkage, ODR, Modules, Namespaces |
| Code Conventions | reference/07_code_conventions.md | Ch 14: Project Organization, Style, Naming |
| Debugging | reference/08_debugging_testing.md | Ch 15: Debuggers, Sanitizers, Testing, TDD |
| Ecosystem | reference/09_ecosystem.md | Ch 16: CMake, Doxygen, Tools |
| Utilities | reference/10_utilities.md | Ch 17: I/O, Strings, Random, Time, Filesystem |
| STL | reference/11_containers_algorithms.md | Ch 18: Containers, Iterators, Algorithms, Ranges |
| Advanced | reference/12_advanced_topics.md | Ch 19-20: Move Semantics, Smart Pointers, Concurrency |
| Optimization | reference/13_optimization.md | Ch 21-23: Architecture, Code Opt, Profiling |
| Design | reference/14_software_design.md | Ch 24-25: SOLID, Design Patterns, C++ Idioms |
| Performance | reference/abseil_performance_hints_report.md | Google Abseil Performance Hints (Jeff Dean),性能审计理论 |
Core Philosophy (from Chapter 1)
When approaching any C++ task, keep these principles in mind:
Zero Overhead Principle
"Do not sacrifice performance except as a last resort." Abstractions should not cost anything compared to writing equivalent lower-level code. A matrix multiply written in high-level C++ should be as fast as raw C with arrays and pointers.
Compile-Time Safety
Enforce safety at compile time whenever possible. C++ is statically typed — the compiler catches bugs at compile time instead of runtime. Type annotations make code more readable and enable compiler optimizations.
Multi-Paradigm
C++ supports procedural, object-oriented, generic, and functional programming. Choose the right paradigm for each problem rather than forcing a single approach.
Full Control
C++ provides control over every aspect: memory layout, allocation strategy, instruction selection. No garbage collector, no dynamic type system — predictable runtime behavior suitable for real-time systems.
Working with C++ Code
When Writing C++ Code
-
Determine the target standard: Check what C++ standard the project uses. Prefer the latest available (C++20/23) for new projects, but respect existing codebase standards.
-
Use modern idioms first:
- Prefer
auto for type deduction where it improves readability
- Use range-based
for loops over raw index loops
- Use smart pointers (
unique_ptr, shared_ptr) over raw pointers
- Use
nullptr instead of NULL or 0
- Use
constexpr for compile-time computation
- Use lambdas instead of raw function objects
-
Follow the Rule of Five/Zero:
- Rule of Zero: If a class doesn't manage resources directly, declare no special member functions
- Rule of Five: If you define any of {destructor, copy ctor, copy assignment, move ctor, move assignment}, define all five
-
Const correctness: Mark everything const by default. Use const& for parameters that shouldn't be modified. Use const member functions for methods that don't modify state.
-
Error Handling Strategy:
- Use exceptions for truly exceptional errors
- Use
std::expected (C++23) or std::optional for recoverable errors
- Use return codes only at C API boundaries
- Mark noexcept where appropriate
-
Performance awareness:
- Pass by value for small, trivially-copyable types (≤ 8 bytes)
- Pass by const reference for large objects
- Use
std::move for transferring ownership
- Reserve vector capacity when size is known
- Prefer
emplace_back over push_back
When Reviewing C++ Code
Check for:
- Memory leaks (prefer RAII, smart pointers)
- Undefined behavior (signed overflow, null dereference, use-after-move)
- Missing
const on parameters and methods
- Unnecessary copies (pass by value instead of const reference)
- Missing
noexcept on move constructors
- Virtual destructor in base classes
- Proper use of
= default and = delete
- Inclusion of proper headers
- Namespace pollution (prefer anonymous namespaces over
static)
When Debugging C++ Code
- Enable all warnings:
-Wall -Wextra -Wpedantic (gcc/clang), /W4 (MSVC)
- Use sanitizers: AddressSanitizer, UndefinedBehaviorSanitizer, LeakSanitizer, MemorySanitizer
- Static analysis:
clang-tidy, cppcheck, Coverity
- Runtime checks:
valgrind (memcheck), gdb/lldb for step debugging
- Hardening:
-D_GLIBCXX_ASSERTIONS, -fstack-protector-strong, -D_FORTIFY_SOURCE=2
C++ Standard Quick Reference
C++11 Highlights
auto, range-for, lambdas, nullptr, constexpr, move semantics, smart pointers, std::thread, uniform initialization, = default/= delete, override/final, enum class, static_assert, variadic templates
C++14 Highlights
Generic lambdas (auto parameters), decltype(auto), std::make_unique, binary literals, digit separators, variable templates
C++17 Highlights
Structured bindings, if constexpr, std::optional, std::variant, std::any, std::string_view, fold expressions, CTAD, [[nodiscard]], inline variables, constexpr lambdas
C++20 Highlights
Concepts, ranges, coroutines, modules, std::format, std::span, consteval, constinit, spaceship operator <=>, [[likely]]/[[unlikely]], std::source_location, designated initializers, contains() for containers
C++23 Highlights
std::expected, std::mdspan, std::print, if consteval, [[assume]], auto(x) decay-copy, range adaptors improvements, std::stacktrace
C++26 (Upcoming)
Reflection, contracts, pattern matching, more constexpr support
Quick Reference: Common Patterns
Pass-by Semantics Decision Tree
Is the type ≤ 8 bytes and trivially copyable?
YES → Pass by value (int, double, small structs)
NO → Is ownership being transferred?
YES → Pass by rvalue reference (T&&) or value + std::move
NO → Pass by const reference (const T&)
Special Member Function Generation Rules
User declares nothing → All 5 generated (Rule of Zero)
User declares destructor → Copy ops generated (deprecated), Move ops NOT generated
User declares copy constructor → Move ops NOT generated
User declares move constructor → Copy ops = delete
User declares copy assignment → Move ops NOT generated
User declares move assignment → Copy ops = delete
Smart Pointer Decision
Exclusive ownership? → std::unique_ptr
Shared ownership needed? → std::shared_ptr
Break circular reference? → std::weak_ptr
No ownership, just observing? → Raw pointer or reference (T* or T&)
Container Selection Flowchart
Need index-based access? → std::vector (or std::array for fixed size)
Need fast insertion at both ends? → std::deque
Need sorted, unique keys? → std::set / std::map
Need sorted, non-unique keys? → std::multiset / std::multimap
Need unsorted, unique keys? → std::unordered_set / std::unordered_map
Need LIFO? → std::stack
Need FIFO? → std::queue
Need priority? → std::priority_queue
Need stable memory addresses? → std::list
Need very small size? → std::forward_list
Performance Optimization (Abseil Performance Hints)
做性能审计时,逐条检查以下清单。这是本技能最重要的审计工具。理论全文见 reference/abseil_performance_hints_report.md。
1. 内存分配检查 (Abseil §7)
2. 热路径检查 (Abseil §8)
3. 日志检查 (Abseil §11)
4. 内存布局检查 (Abseil §6)
5. 编译器辅助检查 (Abseil §9)
6. 并行化与同步检查 (Abseil §13)
7. Protobuf 专项检查 (Abseil §14)
8. 容器选择检查 (Abseil §15)
性能审计流程
当用户要求对 C++ 代码做性能审计时:
- 定位文件: 确定要审计的文件
- 识别热点: 判断是否在控制循环/实时路径/高频回调中
- 加载性能理论: 按需读
reference/abseil_performance_hints_report.md 相关章节
- 逐条检查: 按上述 8 类检查清单逐项过(内存分配 → 热路径 → 日志 → 布局 → 编译器 → 并行 → protobuf → 容器)
- 输出报告: 按格式输出
审计报告格式
## 性能审计: <文件路径>
### 代码位置: <模块/子系统,实时路径?>
### 检查结果
- **严重**: <违反 abseil 规则的性能问题>
- **警告**: <潜在性能风险>
- **改进建议**: <具体修改方案,含代码示例>
### 检查清单覆盖
- [x] 内存分配: <结论>
- [x] 热路径: <结论>
- [x] 日志: <结论>
- [ ] 内存布局: <结论>
- [x] 编译器辅助: <结论>
- [ ] 并行化: <结论>
- [x] Protobuf: <结论>
- [x] 容器选择: <结论>
### 预期收益: <基于 abseil 案例的量化估计>
代码审查清单(现代 C++ 质量)
除性能外,还要检查现代 C++ 代码质量。注意:即使是"代码审查"请求(未明确说"性能审计"),也必须同时应用 Abseil 检查清单中与本段代码相关的项(内存分配、热路径、日志、protobuf 复用)——纯正确性审查而忽略性能问题是失职的。审查报告应按"性能发现 + 正确性发现"两部分输出。
1. 智能指针与 RAII
2. 移动语义
3. 类型安全
4. 模板与现代特性
5. 并发
When to Read Reference Files
- Writing class hierarchies → Read
reference/04_oop.md
- Writing templates or generic code → Read
reference/05_templates.md
- Organizing project files/headers → Read
reference/06_translation_units.md and reference/07_code_conventions.md
- Setting up CMake build → Read
reference/09_ecosystem.md
- Debugging crashes/memory issues → Read
reference/08_debugging_testing.md
- Optimizing performance-critical code → Read
reference/13_optimization.md and reference/abseil_performance_hints_report.md
- Designing software architecture → Read
reference/14_software_design.md
- Using STL containers/algorithms → Read
reference/11_containers_algorithms.md
- Working with I/O, strings, time, filesystem → Read
reference/10_utilities.md
- Move semantics and perfect forwarding → Read
reference/12_advanced_topics.md