C++ Design Best Practices
Overview
Use this skill to keep C++ code practical and safe: explicit ownership, strong API boundaries, predictable error handling, and measurable performance.
Core rules
- Prefer RAII for all resource lifetimes.
- Make ownership obvious at type boundaries (
unique_ptr, references, value types). - Keep interfaces small and stable.
- Use
constand immutability by default. - Avoid hidden global state.
Design guidance
- Separate pure logic from I/O and side effects.
- Make invalid states unrepresentable with types where possible.
- Favor composition over deep inheritance.
- Keep headers minimal to reduce coupling and rebuild cost.
- Hide platform-specific code behind narrow adapters.
Error and API conventions
- Prefer explicit status/exception policy per module (do not mix ad hoc).
- Do not throw across C ABI boundaries.
- Validate inputs early and return actionable diagnostics.
- Keep error messages stable enough for CI/debugging.
Performance hygiene
- Measure first; optimize real hotspots.
- Avoid accidental allocations in hot loops.
- Keep data layouts cache-friendly.
- Re-check branchy code with representative workloads before and after changes.
Concurrency hygiene
- Prefer message passing or clear lock ownership over ad hoc shared mutable state.
- Keep critical sections short.
- Document thread-safety guarantees for each public type.
- Use sanitizers and thread tooling in CI where feasible.
Code review checklist
- Are ownership and lifetimes explicit?
- Are ABI/error boundaries safe?
- Are tests focused on behavior and regressions?
- Are performance claims backed by data?
- Is the design simple enough for future contributors?
Learn more (official)
- C++ Core Guidelines: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
- CMake best practices (official docs): https://cmake.org/cmake/help/latest/
- Clang-Tidy checks: https://clang.llvm.org/extra/clang-tidy/
- C++ reference (language/library): https://en.cppreference.com/
微信扫一扫