返回 Skill 列表
extension
分类: 开发与工程无需 API Key

cpp-core-guidelines

由Stroustrup和Sutter编写的C++核心指南,用于编写现代、安全且高效的C++代码。在编写、审查或重构C++代码时使用,以确保类型安全、资源安全和性能。触发于包括接口设计、资源管理(内存、句柄、锁)、类设计、错误处理、并发性、模板以及一般代码审查在内的C++代码任务。适用于诸如“审查这段C++代码”、“我应该如何在C++中管理资源?”、“C++接口的最佳实践是什么?”等问题,或者当按照现代标准(C++11/14/17/20)编写任何C++代码时。

person作者: jakexiaohubgithub

C++ Core Guidelines

Overview

These guidelines help write C++ code that is:

  • Type-safe: No implicit violations of the type system
  • Resource-safe: No leaks (memory, handles, locks, etc.)
  • Performant: Efficient without sacrificing correctness
  • Correct: Catches more logic errors at compile time

Load Reference by Scenario

Choose the reference file based on what you're doing:

| Scenario | Reference File | Rules | |----------|----------------|-------| | Checking memory leaks, RAII, pointers | memory-safety.md | R., ES., Con.* | | Designing function signatures, APIs | api-design.md | I., F. | | Designing or reviewing classes | class-design.md | C.* | | Thread safety, data races, locks | concurrency.md | CP.* | | Exceptions, error codes, error handling | error-handling.md | E.* | | Templates, STL, generic code | templates.md | T., SL., Enum.* | | Coding style, naming, philosophy | modern-style.md | P., NL., SF.* | | Performance optimization, C compatibility | performance.md | Per., CPL., A.* |

Quick Reference

Memory Safety

// Bad: manual management
X* p = new X;
delete p;

// Good: RAII
auto p = make_unique<X>();

API Design

// Bad: unclear ownership
void process(int* data, int n);

// Good: explicit ownership and size
void process(span<const int> data);

Class Design

// Rule of zero - let compiler generate
class Widget {
    unique_ptr<Impl> pImpl;  // No explicit dtor/copy/move needed
};

Concurrency

// Bad: manual lock
mutex mtx;
mtx.lock();
// ...
mtx.unlock();

// Good: RAII lock
lock_guard<mutex> lock(mtx);

Code Review Checklist

When reviewing C++ code, load the appropriate reference and check:

Memory Safetymemory-safety.md

  • [ ] No raw new/delete
  • [ ] RAII for all resources
  • [ ] No dangling pointers
  • [ ] Proper const usage

API Designapi-design.md

  • [ ] Interfaces are explicit
  • [ ] Parameters express ownership
  • [ ] Return values over output params

Class Designclass-design.md

  • [ ] Class has clear invariant
  • [ ] Rule of zero/five followed
  • [ ] Virtual destructor for base classes

Thread Safetyconcurrency.md

  • [ ] No data races
  • [ ] lock_guard/scoped_lock used
  • [ ] No deadlocks