@chengzhao-dev/dsh-cpp-workflow 0.6.19 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.en.md +11 -26
  2. package/README.md +13 -28
  3. package/cordis.patch.yml +1 -1
  4. package/lib/client.js +33 -21
  5. package/lib/comment-policy.js +15 -6
  6. package/lib/index.js +1 -1
  7. package/lib/workspace.js +0 -15
  8. package/package.json +7 -7
  9. package/skills/building-cpp/SKILL.md +34 -21
  10. package/skills/building-cpp/assets/templates/projects/common/running-build.sh +5 -1
  11. package/skills/building-cpp/project/vscode/01-extensions.md +28 -0
  12. package/skills/building-cpp/project/vscode/02-settings.md +39 -0
  13. package/skills/building-cpp/references/build-script.md +14 -7
  14. package/skills/building-cpp/references/environment.md +8 -1
  15. package/skills/building-cpp/steps/01-build.md +8 -8
  16. package/skills/building-cpp/steps/02-tooling.md +17 -9
  17. package/skills/building-cpp/steps/03-check.md +16 -14
  18. package/skills/developing-cpp/SKILL.md +37 -25
  19. package/skills/developing-cpp/references/comments/comment-rules.md +181 -0
  20. package/skills/developing-cpp/references/comments/comment-style.md +80 -0
  21. package/skills/developing-cpp/references/comments/examples/declaration-class.md +66 -0
  22. package/skills/developing-cpp/references/comments/examples/declaration-constructor.md +22 -0
  23. package/skills/developing-cpp/references/comments/examples/declaration-enum.md +48 -0
  24. package/skills/developing-cpp/references/comments/examples/declaration-file.md +66 -0
  25. package/skills/developing-cpp/references/comments/examples/declaration-function.md +127 -0
  26. package/skills/developing-cpp/references/comments/examples/declaration-member.md +23 -0
  27. package/skills/developing-cpp/references/comments/examples/declaration-predicate.md +14 -0
  28. package/skills/developing-cpp/references/comments/examples/declaration-struct.md +18 -0
  29. package/skills/developing-cpp/references/comments/examples/implementation-body.md +64 -0
  30. package/skills/developing-cpp/references/comments/examples/implementation-todo.md +16 -0
  31. package/skills/developing-cpp/references/comments/glossary/comment-terms.md +93 -0
  32. package/skills/developing-cpp/references/design/examples/behavior-sentence.md +14 -0
  33. package/skills/developing-cpp/references/design/examples/coordinate-table.md +31 -0
  34. package/skills/developing-cpp/references/design/examples/header-place.md +26 -0
  35. package/skills/developing-cpp/references/design/examples/library-boundary.md +30 -0
  36. package/skills/developing-cpp/references/design/examples/library-split.md +7 -0
  37. package/skills/developing-cpp/references/design/examples/move-result.md +39 -0
  38. package/skills/developing-cpp/references/design/examples/preview-read.md +40 -0
  39. package/skills/developing-cpp/references/{project-design.md → design/project-design.md} +57 -5
  40. package/skills/developing-cpp/references/{change-model.md → editing/01-edit-operations.md} +5 -3
  41. package/skills/developing-cpp/references/{priority.md → editing/02-rule-priority.md} +2 -2
  42. package/skills/developing-cpp/references/exceptions/examples/throw-boundary.md +28 -0
  43. package/skills/developing-cpp/references/exceptions/examples/throw-build-mode.md +38 -0
  44. package/skills/developing-cpp/references/exceptions/examples/throw-catch.md +21 -0
  45. package/skills/developing-cpp/references/exceptions/examples/throw-destructor.md +21 -0
  46. package/skills/developing-cpp/references/exceptions/examples/throw-format.md +13 -0
  47. package/skills/developing-cpp/references/exceptions/examples/throw-message.md +16 -0
  48. package/skills/developing-cpp/references/exceptions/examples/throw-when.md +27 -0
  49. package/skills/developing-cpp/references/{exceptions.md → exceptions/throw-rules.md} +78 -23
  50. package/skills/developing-cpp/references/{glossary.md → language/glossary/language-terms.md} +2 -2
  51. package/skills/developing-cpp/references/language/language-basics/01-objects.md +15 -0
  52. package/skills/developing-cpp/references/language/language-basics/02-initialization.md +26 -0
  53. package/skills/developing-cpp/references/language/language-basics/03-deduction.md +12 -0
  54. package/skills/developing-cpp/references/language/language-basics/04-const.md +25 -0
  55. package/skills/developing-cpp/references/language/language-basics/05-expressions.md +23 -0
  56. package/skills/developing-cpp/references/language/language-basics/06-functions.md +15 -0
  57. package/skills/developing-cpp/references/language/language-basics/07-classes.md +15 -0
  58. package/skills/developing-cpp/references/language/language-basics/08-raii.md +15 -0
  59. package/skills/developing-cpp/references/language/language-basics/09-templates.md +26 -0
  60. package/skills/developing-cpp/references/language/language-basics/10-checklist.md +10 -0
  61. package/skills/developing-cpp/references/language/performance/01-measure.md +22 -0
  62. package/skills/developing-cpp/references/language/performance/02-complexity.md +13 -0
  63. package/skills/developing-cpp/references/language/performance/03-memory.md +14 -0
  64. package/skills/developing-cpp/references/language/performance/04-undefined-behavior.md +28 -0
  65. package/skills/developing-cpp/references/language/performance/05-pitfalls.md +17 -0
  66. package/skills/developing-cpp/references/language/performance/06-false-optimizations.md +13 -0
  67. package/skills/developing-cpp/references/language/performance/07-checklist.md +8 -0
  68. package/skills/developing-cpp/references/language/standard-library/01-containers.md +29 -0
  69. package/skills/developing-cpp/references/language/standard-library/02-access.md +14 -0
  70. package/skills/developing-cpp/references/language/standard-library/03-iteration.md +18 -0
  71. package/skills/developing-cpp/references/language/standard-library/04-algorithms.md +26 -0
  72. package/skills/developing-cpp/references/language/standard-library/05-string.md +13 -0
  73. package/skills/developing-cpp/references/language/standard-library/06-format.md +106 -0
  74. package/skills/developing-cpp/references/language/standard-library/07-time.md +13 -0
  75. package/skills/developing-cpp/references/language/standard-library/08-random.md +13 -0
  76. package/skills/developing-cpp/references/language/standard-library/09-files.md +14 -0
  77. package/skills/developing-cpp/references/language/standard-library/10-checklist.md +9 -0
  78. package/skills/developing-cpp/references/language/value-types/01-width.md +17 -0
  79. package/skills/developing-cpp/references/language/value-types/02-signed.md +26 -0
  80. package/skills/developing-cpp/references/language/value-types/03-integer-roles.md +38 -0
  81. package/skills/developing-cpp/references/language/value-types/04-enum.md +24 -0
  82. package/skills/developing-cpp/references/language/value-types/05-strong-type.md +17 -0
  83. package/skills/developing-cpp/references/language/value-types/06-const-method.md +22 -0
  84. package/skills/developing-cpp/references/language/value-types/07-nodiscard.md +15 -0
  85. package/skills/developing-cpp/references/language/value-types/08-comparison.md +10 -0
  86. package/skills/developing-cpp/references/language/value-types/09-subscript.md +15 -0
  87. package/skills/developing-cpp/references/language/value-types/10-float-bool.md +13 -0
  88. package/skills/developing-cpp/references/language/value-types/11-checklist.md +8 -0
  89. package/skills/developing-cpp/references/{layout.md → layout/01-source-layout.md} +10 -4
  90. package/skills/developing-cpp/references/{file-template.md → layout/02-file-template.md} +10 -4
  91. package/skills/developing-cpp/references/layout/03-declaration-order.md +138 -0
  92. package/skills/developing-cpp/references/naming/examples/naming-accessor.md +17 -0
  93. package/skills/developing-cpp/references/naming/examples/naming-basic.md +3 -0
  94. package/skills/developing-cpp/references/naming/examples/naming-current-prefix.md +19 -0
  95. package/skills/developing-cpp/references/naming/examples/naming-lookup.md +18 -0
  96. package/skills/developing-cpp/references/naming/examples/naming-lower-layer.md +39 -0
  97. package/skills/developing-cpp/references/naming/examples/naming-multiple-return.md +20 -0
  98. package/skills/developing-cpp/references/naming/examples/naming-player-value.md +16 -0
  99. package/skills/developing-cpp/references/naming/examples/naming-predicate.md +18 -0
  100. package/skills/developing-cpp/references/naming/examples/naming-rename.md +5 -0
  101. package/skills/developing-cpp/references/naming/examples/naming-responsibility.md +19 -0
  102. package/skills/developing-cpp/references/naming/examples/naming-role.md +21 -0
  103. package/skills/developing-cpp/references/naming/examples/naming-state-change.md +57 -0
  104. package/skills/developing-cpp/references/{naming.md → naming/identifier-names.md} +37 -9
  105. package/skills/developing-cpp/references/{google-cpp-style.md → style/google-cpp-style.md} +11 -10
  106. package/skills/developing-cpp/scripts/checking-comments.mjs +71 -14
  107. package/skills/developing-cpp/scripts/checking-declaration-order.mjs +357 -0
  108. package/skills/developing-cpp/steps/01-behavior.md +5 -5
  109. package/skills/developing-cpp/steps/02-boundary.md +10 -10
  110. package/skills/developing-cpp/steps/03-declaration.md +16 -14
  111. package/skills/developing-cpp/steps/04-implementation.md +21 -17
  112. package/skills/engineering/SKILL.md +87 -0
  113. package/skills/{configuring-cmake/assets/cmake → engineering/references/cmake/assets}/CompileSettings.cmake +2 -0
  114. package/skills/{building-cpp/references/linking.md → engineering/references/cmake/linking/01-libraries.md} +7 -48
  115. package/skills/engineering/references/cmake/linking/02-rpath.md +25 -0
  116. package/skills/engineering/references/cmake/linking/03-undefined-reference.md +20 -0
  117. package/skills/engineering/references/cmake/linking/04-inspect.md +21 -0
  118. package/skills/{configuring-cmake/references/modules.md → engineering/references/cmake/modules/functions.md} +8 -5
  119. package/skills/{configuring-cmake/references → engineering/references/cmake/standard}/cxx-standard.md +5 -4
  120. package/skills/engineering/references/cmake/standard/examples/standard.md +19 -0
  121. package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/README.md +9 -9
  122. package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++20/README.md +1 -1
  123. package/skills/engineering/references/cmake/targets/examples/glob.md +22 -0
  124. package/skills/engineering/references/cmake/targets/examples/rpath.md +24 -0
  125. package/skills/{configuring-cmake/examples/cmake.md → engineering/references/cmake/targets/examples/target.md} +2 -70
  126. package/skills/{configuring-cmake/references/cmake.md → engineering/references/cmake/targets/rules.md} +18 -11
  127. package/skills/{building-cpp/references/testing.md → engineering/references/cmake/testing/ctest.md} +11 -4
  128. package/skills/{building-cpp/references/encoding.md → engineering/references/formatting/01-encoding.md} +1 -1
  129. package/skills/engineering/references/formatting/02-clang-format.md +20 -0
  130. package/skills/engineering/references/formatting/03-clang-tidy.md +58 -0
  131. package/skills/engineering/references/formatting/04-clangd.md +90 -0
  132. package/skills/engineering/references/formatting/examples/clang-format.md +38 -0
  133. package/skills/engineering/references/formatting/examples/clang-tidy.md +43 -0
  134. package/skills/{building-cpp/examples/tooling.md → engineering/references/formatting/examples/clangd.md} +1 -80
  135. package/skills/{configuring-cmake → engineering}/steps/01-targets.md +6 -6
  136. package/skills/{configuring-cmake → engineering}/steps/02-modules.md +4 -4
  137. package/skills/{configuring-cmake → engineering}/steps/03-check.md +3 -2
  138. package/templates/cpp-workflow-project/SKILL.md +1 -1
  139. package/skills/building-cpp/references/static-analysis.md +0 -148
  140. package/skills/configuring-cmake/SKILL.md +0 -68
  141. package/skills/developing-cpp/examples/comments-declaration.md +0 -313
  142. package/skills/developing-cpp/examples/comments-implementation.md +0 -66
  143. package/skills/developing-cpp/examples/exceptions.md +0 -173
  144. package/skills/developing-cpp/examples/naming.md +0 -168
  145. package/skills/developing-cpp/examples/structure.md +0 -194
  146. package/skills/developing-cpp/references/comment-terms.md +0 -75
  147. package/skills/developing-cpp/references/comments.md +0 -223
  148. package/skills/developing-cpp/references/declaration-order.md +0 -118
  149. package/skills/developing-cpp/references/language.md +0 -123
  150. package/skills/developing-cpp/references/performance.md +0 -83
  151. package/skills/developing-cpp/references/standard-library.md +0 -138
  152. package/skills/developing-cpp/references/types.md +0 -154
  153. /package/skills/{configuring-cmake/assets/cmake → engineering/references/cmake/assets}/LinkSettings.cmake +0 -0
  154. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++11/README.md +0 -0
  155. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++11/cmake-snippet.cmake +0 -0
  156. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++14/README.md +0 -0
  157. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++14/cmake-snippet.cmake +0 -0
  158. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++17/README.md +0 -0
  159. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++17/cmake-snippet.cmake +0 -0
  160. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++20/cmake-snippet.cmake +0 -0
  161. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++23/README.md +0 -0
  162. /package/skills/{building-cpp/references → engineering/references/cmake/standard}/standards/c++23/cmake-snippet.cmake +0 -0
  163. /package/skills/{building-cpp → engineering/references/formatting}/scripts/checking-encoding.mjs +0 -0
@@ -0,0 +1,21 @@
1
+ # 正反例:析构
2
+
3
+ **差**:
4
+
5
+ ```cpp
6
+ ~Writer() {
7
+ if (file_) file_->Flush(); // 失败时抛?析构中抛会终止程序
8
+ }
9
+ ```
10
+
11
+ **好**:
12
+
13
+ ```cpp
14
+ ~Writer() {
15
+ if (file_) {
16
+ file_->Flush(); // 忽略失败:析构不抛,错误由 Close() 报告
17
+ }
18
+ }
19
+ ```
20
+
21
+ 需要报告关闭失败时,提供显式 `Close()` 返回结果,析构只做兜底。
@@ -0,0 +1,13 @@
1
+ # 正反例:`std::format` 与 `std::print`
2
+
3
+ C++23 且标准库支持 `std::print` 时,程序入口或 CLI 可以写:
4
+
5
+ ```cpp
6
+ std::print("任务: {}\n", task.name);
7
+ ```
8
+
9
+ 库代码、以及需要兼容 C++11–C++20 的代码仍写:
10
+
11
+ ```cpp
12
+ std::cout << std::format("任务: {}\n", task.name);
13
+ ```
@@ -0,0 +1,16 @@
1
+ # 正反例:异常类型与消息
2
+
3
+ **差**:抛字符串,或把来源、条件和值揉成一句口语;调用方接到的 `what()` 既不稳定,也无法定位是哪一步失败。
4
+
5
+ ```cpp
6
+ throw "bad index";
7
+ throw std::out_of_range{std::format("GetTask: 下标 {} 越界", index)};
8
+ ```
9
+
10
+ **好**:语义已经由标准类型给出时直接用标准类型;消息按「标签: 完整句」组织,句子主语是失败的值,实际值直接插进句子,限度用 `for` 接在后面;语言由项目约定,入口需要面向用户的前缀时只加前缀。
11
+
12
+ ```cpp
13
+ throw std::out_of_range{std::format("GetTask: index {} is out of range", index)};
14
+ ```
15
+
16
+ 消息写操作和关键值;英文消息小写开头、句末不加句号,中文消息按中文标点,句式不变;实际值用 `{}` 直接放进句子,不要写成 `(index={})`。`std::format` 只是构造消息的方式,句式见 `references/exceptions/throw-rules.md` 的「消息」节。项目若定义 `Error` 基类,按该文件先定基类再派生,调用方捕获基类接住整族。
@@ -0,0 +1,27 @@
1
+ # 正反例:什么时候抛
2
+
3
+ 这些例子只用于开发阶段讨论源码写法。插件运行时不编译它们,也不执行它们。
4
+
5
+ **差**:用户输入格式错误是调用方每天都要处理的正常结果,却用异常表达,调用方被迫用 `try/catch` 做分支。
6
+
7
+ ```cpp
8
+ Task ParseTask(std::string_view line); // 任何格式错误都抛
9
+ ```
10
+
11
+ **好**:接口把「解析可能失败」写进返回类型;只有函数无法完成自己的任务、继续执行没有意义时才抛。
12
+
13
+ ```cpp
14
+ enum class ParseStatus { kOk, kEmptyLine, kMissingPriority, kBadPriority };
15
+
16
+ struct ParseResult {
17
+ std::optional<Task> task;
18
+ ParseStatus status = ParseStatus::kEmptyLine;
19
+ };
20
+
21
+ [[nodiscard]] ParseResult TryParseTask(std::string_view line);
22
+
23
+ /// @throws std::out_of_range index 不在 [0, size()) 内。
24
+ [[nodiscard]] Task GetTask(int index) const;
25
+ ```
26
+
27
+ `TryParseTask` 把失败作为正常结果返回。`GetTask` 的前提是调用方给出有效下标;越界时函数无法返回一个任务,抛标准库已有的 `std::out_of_range`。如果越界其实是正常输入,应该改成返回 `std::optional<Task>`,而不是让调用方捕获异常;只有项目需要把这种越界和别处的 `out_of_range` 区分开时,才定义派生类。
@@ -6,8 +6,10 @@ Google C++ Style Guide 明确写「We do not use C++ exceptions」。本工作
6
6
 
7
7
  规范来源:
8
8
 
9
- - [C++ Core Guidelines: Error handling](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-errors)(E.1–E.31)。
9
+ - [C++ Core Guidelines: Error handling](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-errors)(E.1–E.31)。
10
10
  - [Boost.Exception](https://www.boost.org/doc/libs/latest/libs/exception/doc/boost-exception.html):异常类型层级的工程典范,只借它的结构,不把 Boost 变成依赖。
11
+ - [ISO C++ `[except]`](https://eel.is/c++draft/except):异常对象、栈展开与构造/析构期间的规则。
12
+ - [cppreference: Exceptions](https://en.cppreference.com/w/cpp/language/exceptions):异常安全保证与 `noexcept` 的语法参考。
11
13
 
12
14
  ## 先定错误策略
13
15
 
@@ -15,7 +17,7 @@ E.1 要求尽早决定错误处理策略:先问调用方还能不能继续、
15
17
 
16
18
  策略一旦定下,声明、实现、测试和入口都用同一套;不要在同一层里一半返回错误码、一半抛异常。
17
19
 
18
- 判断是否算「混用」,看函数合同而不是看返回类型:查询必须产出一个值、失败时产不出(如 `GetState` 越界),就抛;写入操作把「这次不写」当作正常结果、调用方本来就要分支(如 `Board::Place` 返回 `Cell::SetStateResult::kOccupied`,`CheckPlaceable` 返回具体原因),就用返回值。动作可能因为多个前置条件失败、而调用方需要区分原因时,返回 `enum class` 而不是 `bool` 加输出参数。两者并存时,公共头必须把「拒绝」与「抛」的边界各写一行;没有这行注释才算混用。
20
+ 判断是否算「混用」,看函数合同而不是看返回类型:查询必须产出一个值、失败时产不出(如 `GetSquare` 坐标越界),就抛;写入操作把「这次不写」当作正常结果、调用方本来就要分支(如 `Board::Place` 返回 `Square::PlaceResult`,`Square::Place` 返回 `kOccupied`),就用返回值。动作可能因为多个前置条件失败、而调用方需要区分原因时,返回 `enum class` 而不是 `bool` 加输出参数。两者并存时,公共头必须把「拒绝」与「抛」的边界各写一行;没有这行注释才算混用。
19
21
 
20
22
  ## 什么时候抛
21
23
 
@@ -32,27 +34,61 @@ E.2:函数不能完成它被分配的任务时,就抛异常;构造函数
32
34
  3. 下层自己的检查:坐标范围、格子是否为空由 `Board::Place` 判断;不要为了提前抛出而在 `Game` 里重复 `Board::IsInRange`。
33
35
  4. 执行操作并返回结果。
34
36
 
35
- 本层负责的抛出检查必须排在「返回正常失败」之前。否则终局会先返回 `kFinished`,把「不是当前玩家」一起吞掉,调用方拿不到真正的调用错误。属于下层的检查不在此列:对局已结束时 `Game` 不再进入棋盘,越界坐标随 `kFinished` 一起返回,这是正常的短路,不是遗漏。
37
+ 本层负责的抛出检查必须排在「返回正常失败」之前。否则终局会先返回 `kDenied`,把「不是当前玩家」一起吞掉,调用方拿不到真正的调用错误。属于下层的检查不在此列:对局已结束时 `Game` 不再进入棋盘,越界坐标随 `kDenied` 一起返回,这是正常的短路,不是遗漏。
36
38
 
37
39
  参数之间按固定的语义顺序排,不要求与声明顺序一致;关键是同一函数内不来回换,注释、测试和消息都按这个次序。
38
40
 
39
41
  ```cpp
40
- Game::MoveResult Game::Place(Move move) {
41
- if (move.player != current_player_) {
42
+ Game::PlaceResult Game::Place(Move move) {
43
+ if (current_player_ != move.player) {
42
44
  throw std::logic_error{std::format(
43
- "Game::Place: move player is not the current player (move={}, current={})",
44
- move, current_player_)};
45
+ "Game::Place: current player {} cannot accept move {}", current_player_, move)};
45
46
  }
46
- if (board_.GetGameResult() != GameResult::kInProgress) {
47
- return MoveResult::kFinished;
47
+ if (board_.GetStatus() != BoardStatus::kInProgress) {
48
+ return PlaceResult::kDenied;
48
49
  }
49
- // 坐标范围与占用由 Board::Place 检查。
50
- const Cell::SetStateResult result = board_.Place(move.position, PlayerToCellState(move.player));
51
- // 按 result 写历史、返回占用或抛出棋盘拒绝。
50
+ // 坐标范围由 Board 抛出;占用与空值由 Board::Place 返回。
51
+ const Square::PlaceResult result =
52
+ board_.Place(move.position, PlayerToSquareValue(move.player));
53
+ if (result == Square::PlaceResult::kOccupied) {
54
+ return PlaceResult::kRejected;
55
+ }
56
+ if (result == Square::PlaceResult::kIgnored) {
57
+ throw std::logic_error{"Game::Place: board rejected an empty value"};
58
+ }
59
+ // 记录这一步并轮到对方。
52
60
  }
53
61
  ```
54
62
 
55
- 依据:[Core Guidelines I.5](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-pre)、[I.6](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-expects) 把前置条件写进接口;标准库的 `vector::at` 与 `std::stoi` 在访问前检查边界,.NET 的 [CA1062](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1062) 也要求先验证再使用。[P2053R0](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2053r0.pdf) 区分输入校验与防御性检查:外部输入必须校验,内部前置条件可用断言或 contract 表达。这里只把 `Game` 自己拥有的状态前置条件写成异常;`Player` 的取值由适配层保证,坐标范围由 `Board` 拥有,重复检查会让同一规则出现两份,消息与异常类型还可能分叉。参数非法时返回一个业务结果,会让调用方以为「只是不能下这里」,而不是「这手棋本身不成立」。
63
+ ### 重复的入口检查
64
+
65
+ 同一层有多个入口重复同一个 `if (!IsInRange(...)) throw ...` 时,把检查收进私有函数。函数名由调用方传入,`std::source_location` 只在默认参数里取调用点:
66
+
67
+ ```cpp
68
+ void Board::CheckInRange(Position pos, std::string_view function,
69
+ std::source_location location) {
70
+ if (IsInRange(pos)) {
71
+ return;
72
+ }
73
+
74
+ // 不同编译器给出的路径形态不同,只保留文件名,保证消息一致。
75
+ std::string_view file = location.file_name();
76
+ if (const std::size_t separator = file.find_last_of("/\\");
77
+ separator != std::string_view::npos) {
78
+ file.remove_prefix(separator + 1);
79
+ }
80
+
81
+ throw std::out_of_range{std::format(
82
+ "{}: position {} is out of range for board {}x{} ({}:{})", function, pos, kRowCount,
83
+ kColumnCount, file, location.line())};
84
+ }
85
+ ```
86
+
87
+ 声明写成 `static void CheckInRange(Position pos, std::string_view function, std::source_location location = std::source_location::current());`。`source_location::current()` 作为默认参数在调用点求值,所以不把 `source_location` 加进公共接口;标签仍由调用点显式传入,如 `CheckInRange(pos, "Board::Place")`。
88
+
89
+ `source_location` 是 C++20 设施,GCC、Clang 与 MSVC 都提供;差异在 `file_name()` 与 `function_name()` 的内容。`function_name()` 可能给出完整签名或限定名,所以消息标签仍显式传入;`file_name()` 可能是相对或绝对路径,先取 basename。Clang 16 起 `line()` 才稳定指向调用点,MSVC 18.4 起才修复默认参数里直接调用 `.function_name()` 返回空串的问题;传整个 `source_location` 对象可避开后者。这样三个平台都输出 `board.cpp:行号`,测试只断言文件名与函数名,不断言具体行号。
90
+
91
+ 依据:[Core Guidelines I.5](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#ri-pre)、[I.6](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#ri-expects) 把前置条件写进接口;标准库的 `vector::at` 与 `std::stoi` 在访问前检查边界,.NET 的 [CA1062](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1062) 也要求先验证再使用。[P2053R0](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2053r0.pdf) 区分输入校验与防御性检查:外部输入必须校验,内部前置条件可用断言或 contract 表达。这里只把 `Game` 自己拥有的状态前置条件写成异常;`Player` 的取值由适配层保证,坐标范围由 `Board` 拥有,重复检查会让同一规则出现两份,消息与异常类型还可能分叉。参数非法时返回一个业务结果,会让调用方以为「只是不能下这里」,而不是「这手棋本身不成立」。
56
92
 
57
93
  ## 异常类型
58
94
 
@@ -89,7 +125,7 @@ E.31:`catch` 子句从派生到基类、从具体到通用排序,`catch (...
89
125
 
90
126
  ## 不抛的边界
91
127
 
92
- E.12:在不可能或不可接受抛异常的地方用 `noexcept`。声明前先读实现:函数体里出现 `at()` 或其他可能抛出的调用,就去掉 `noexcept`;不要再包一层只转发下标的私有函数来维持 `noexcept`,直接写 `cells_.at(row).at(col)` 并去掉 `noexcept`。正例是只比较两个整数的 `IsInRange`;反例是用 `at()` 读取并会抛 `std::out_of_range` 的 `GetState`。普通查询和返回结果枚举的函数,不因为当前函数体不抛就补 `noexcept`;`noexcept` 留给移动、交换、析构,以及已经标上的纯谓词。E.13:直接拥有资源的函数不要抛,资源释放应交给 RAII。E.16:析构、`deallocate`、`swap` 以及异常类型的拷贝/移动构造不得失败;析构和 `swap` 应当是 `noexcept`。
128
+ E.12:在不可能或不可接受抛异常的地方用 `noexcept`。声明前先读实现:函数体里出现 `at()` 或其他可能抛出的调用,就去掉 `noexcept`;不要再包一层只转发下标的私有函数来维持 `noexcept`,直接写 `squares_.at(row).at(col)` 并去掉 `noexcept`。正例是只比较两个整数的 `IsInRange`;反例是用 `at()` 读取并会抛 `std::out_of_range` 的 `GetSquare`。普通查询和返回结果枚举的函数,不因为当前函数体不抛就补 `noexcept`;`noexcept` 留给移动、交换、析构,以及已经标上的纯谓词。E.13:直接拥有资源的函数不要抛,资源释放应交给 RAII。E.16:析构、`deallocate`、`swap` 以及异常类型的拷贝/移动构造不得失败;析构和 `swap` 应当是 `noexcept`。
93
129
 
94
130
  E.30:不要写异常规范(`throw(...)` 之类);C++11 之后用 `noexcept` 表达「不抛」。需要无异常构建时,由项目单独决定,不要把这套异常指导改写成两面都对的模糊话。
95
131
 
@@ -112,26 +148,44 @@ int main() {
112
148
 
113
149
  ## 消息
114
150
 
115
- `what()` 是给程序员看的诊断文本,句式是「标签: 条件 (值); 限度」,四个槽位不动。标签是标识符,成员写 `Type::Function`,自由函数只写函数名,冒号后一个空格;默认参数用 `std::source_location::current()` 在调用点求值时,标签写 `function_name()`,条件、值与限度三槽不变。先写清哪一步失败、失败条件是什么、手上有什么值,再写允许的限度;语言由项目约定,下面的示例用英文。条件不写 Error / Failed,不写空泛的「失败」;有分号时条件必须是带动词的小句,写 `board position is out of range`,不写无动词片段。括号只放导致失败的实际值,写 `name=value`,逗号后一个空格,等号两侧不空格;没有实际值就不写括号。分号后只放限度,且必须自成小句,如 `board is {}x{}`;没有限度就不写分号。
151
+ `what()` 是给程序员看的诊断文本,句式是「标签: 完整句」。标签写明来源,句子主语是失败的值或对象,谓语说明哪里不对,实际值直接插进句子,限度用 `for` 接在句末。标签是标识符,成员写 `Type::Function`,自由函数只写函数名,冒号后一个空格;默认参数用 `std::source_location::current()` 在调用点求值时,标签写调用方显式传入的 `Type::Function`,不解析 `function_name()` 的完整签名。先写哪个值失败,再写失败条件,最后写限度;语言由项目约定,下面的示例用英文。句子要完整:主语和谓语都在,不写 `board position is out of range` 这种重复标签类型的主语,也不把值塞进括号,不写 Error / Failed 或空泛的「失败」。实际值用 `{}` 直接放进句子,不再写 `(name=value)`;没有实际值就不写值,没有限度就不写 `for`。需要原因时用 `because`,不要用分号堆叠。
116
152
 
117
- 下面的英文示例只用 `:`、`()`、`,`、`=`、`;` 五个 ASCII 符号:冒号紧贴标签、后接一个空格;左括号前一个空格、内侧不空;逗号前不空、后一个空格;等号两侧不空;分号写在右括号外、前不空、后一个空格。不用第二个冒号、句号、问号、感叹号、破折号或 `×`;尺寸写 `3x3`,`out of range` 不加连字符。中文消息按中文标点,但槽位顺序和「值只放实际值」不变。
153
+ 英文消息只用 `:`、`()`、`,`、`=` 四个 ASCII 符号:冒号紧贴标签、后接一个空格;括号只放次要值或补充说明;逗号前不空、后一个空格;等号两侧不空。不用第二个冒号、句号、问号、感叹号、破折号或 `×`;句子小写开头,句末不加句号;尺寸写 `3x3`,`out of range` 不加连字符。中文消息按中文标点,但句式与「值在前、限度在后」的顺序不变。
118
154
 
119
- 值对象已有 `std::formatter` 时,格式串直接写 `{}`,不要拆成多个字段;例如 `position={}` 会输出 `position=(-1, 0)`。没有格式化器的类型才拆字段。
155
+ 值对象已有 `std::formatter` 时,格式串直接写 `{}`,不要拆成多个字段;例如 `position {}` 会输出 `position (-1, 0)`。没有格式化器的类型才拆字段。
120
156
 
121
157
  有插值才用 `std::format`,没有洞的消息用字符串字面量。`std::out_of_range` 与 `std::logic_error` 在构造时复制消息,不能把格式化推迟到 `what()`。格式串只填手头的整数和短文本;格式化若抛出,调用方看到 `std::format_error` 或 `std::bad_alloc`,所以不在抛出表达式里做 I/O。自有异常类型才在 `what()` 里惰性格式化并兜底,本仓库不为此新增类型。
122
158
 
123
159
  `what()` 不是分支接口;调用方要数字就放进类型成员,不解析字符串。入口可以在消息前加面向用户的前缀,库代码不打印日志。
124
160
 
161
+ 写进 `throw` 时,直接把 `std::format(...)` 放在异常类型后面,不先建消息变量:
162
+
163
+ ```cpp
164
+ throw std::out_of_range{std::format(
165
+ "Board::GetSquare: position {} is out of range for board {}x{}", pos, kRowCount,
166
+ kColumnCount)};
167
+ ```
168
+
169
+ 跨行时只把格式串与参数续到下一行:`throw`、异常类型与 `std::format(` 留在同一行,读者先看到抛什么,再看到消息。消息没有插值时写一行 `throw std::logic_error{"ChooseSquare: game is already over"};`。
170
+
171
+ 常用库把消息的构造放进异常类型或辅助函数:spdlog 的 `spdlog_ex` 在构造函数里写 `_msg`,CLI11 的 `Error` 族在静态工厂里拼好句子,POCO 的 `Exception` 在构造函数里存消息;调用处因此只有一行 `throw ...(...)`。本工作流不额外引入消息变量,也不为消息的 `const` 与 `std::move` 单独做决定。
172
+
173
+ Rust 把失败分成两类:`Result` 表示可预期的失败,用 `?` 传播;`panic!` 只表示程序里的 bug(invariant 已被破坏),消息同样在调用点构造,长消息由格式化器折行。C++ 的异常同时承担这两种职责,本工作流因此把「调用方无法继续」写成异常,把「可恢复的拒绝」写成返回值。
174
+
125
175
  ```cpp
126
176
  throw std::out_of_range{std::format(
127
- "Board::GetCell: board position is out of range (position={}); board is {}x{}",
128
- position, kRowCount, kColumnCount)};
177
+ "Board::GetSquare: position {} is out of range for board {}x{}", pos, kRowCount,
178
+ kColumnCount)};
179
+
129
180
  throw std::logic_error{std::format(
130
- "Game::Place: board rejected a move with empty state (position={})", move.position)};
131
- throw std::logic_error{"Ai::Choose: game is already over"};
132
- throw std::logic_error{"EmptyCellsOrThrow: no empty cell left to place"};
181
+ "Game::Place: board rejected move {} because the cell state is empty", move)};
182
+
183
+ throw std::logic_error{"ChooseSquare: game is already over"};
184
+ throw std::logic_error{"ChooseSquare: there is no empty square left to place"};
133
185
  ```
134
186
 
187
+ 反例:`Board::GetSquare: board position is out of range (position={}); board is {}x{}`。标签已经说明是 `Board::GetSquare`,句子又用 `board position` 当主语,实际值还放在括号里;读者要在标签、主语和括号之间来回拼。
188
+
135
189
  ## 声明注释
136
190
 
137
191
  在公共声明的注释里写清:什么条件下抛、抛哪一类、调用方如何避免。实现文件里的内部异常不必逐条写进公共头。
@@ -148,10 +202,11 @@ Config ReadConfig(const std::filesystem::path& path);
148
202
  - [ ] 错误策略在接口设计时已确定,同一层没有混用错误码和异常。
149
203
  - [ ] 构造函数失败时抛异常,没有留下半初始化对象。
150
204
  - [ ] 异常类型有语义,没有抛内建类型、字符串或裸指针。
205
+ - [ ] `throw` 直接接收 `std::format(...)`;跨行时只把格式串与参数续行,不为消息单独建变量。
151
206
  - [ ] 按值抛出、按 `const` 引用捕获;重抛用 `throw;`。
152
207
  - [ ] 析构、`swap`、异常类型的拷贝/移动不抛。
153
208
  - [ ] 没有用异常做正常分支,也没有在每个函数里捕获所有异常。
154
- - [ ] 本层负责的参数校验与状态检查排在正常结果返回之前;非法参数没有被 `kFinished` 之类的业务结果掩盖。
209
+ - [ ] 本层负责的参数校验与状态检查排在正常结果返回之前;非法参数没有被 `kDenied` 之类的业务结果掩盖。
155
210
  - [ ] 入口有统一捕获,消息可定位,退出码符合项目合同。
156
211
  - [ ] 公共声明的 `@throws` 与实际抛出类型一致,且 Debug/Release 的抛出条件相同。
157
212
  - [ ] 每个 `noexcept` 函数的函数体不调用 `at()` 或其他会抛的接口。
@@ -1,6 +1,6 @@
1
1
  # 术语
2
2
 
3
- 代码标识符用英文;注释和说明用中文时,同一个概念只用一种译法。下表是本项目的默认译法,项目技能可以增补,但不要改已有词的含义。标识符怎么拼(大小写、前缀、语义角色)见 `references/naming.md`;本表只管术语译法与近义词辨析。
3
+ 代码标识符用英文;注释和说明用中文时,同一个概念只用一种译法。下表是本项目的默认译法,项目技能可以增补,但不要改已有词的含义。标识符怎么拼(大小写、前缀、语义角色)见 `references/naming/identifier-names.md`;本表只管术语译法与近义词辨析。
4
4
 
5
5
  | 英文 | 中文 | 说明 |
6
6
  | --- | --- | --- |
@@ -84,5 +84,5 @@
84
84
  - **声明 vs 定义**:头文件里多是声明;函数体、全局变量初始化是定义。
85
85
  - **参数 vs 实参**:声明里叫参数(parameter),调用点叫实参(argument);中文口语都叫参数时,写文档要区分。
86
86
  - **接口 vs 实现**:公共头是接口,`.cpp` 是实现;不要用「接口」指整个类。
87
- - **异常 vs 错误**:异常是语言机制,错误是结果;是否用异常表达错误由接口合同和 invariant 决定,不能把两者当同义词。规则见 `references/exceptions.md`。
87
+ - **异常 vs 错误**:异常是语言机制,错误是结果;是否用异常表达错误由接口合同和 invariant 决定,不能把两者当同义词。规则见 `references/exceptions/throw-rules.md`。
88
88
  - **格式化 vs 排版**:`std::format` 组合消息;clang-format 排版源码。不要混用「格式化」指代两者。
@@ -0,0 +1,15 @@
1
+ # 值与对象
2
+
3
+ 这里只写“换一台机器、换一个编译器仍然成立”的 C++11–C++23 语言规则;示例默认 C++23,C++11/14/17/20 项目按声明降级。项目专属类型、协议字段和构建目录不在本组条文。
4
+
5
+ - 类型决定允许的操作和表示;对象是某类型的一块存储;值是可以复制、比较、传递的内容。
6
+ - 变量有名字、类型、存储期和作用域。局部变量在离开作用域时销毁;`static` 局部变量在首次执行到声明时初始化,程序结束时销毁。
7
+ - 声明让名字可见,定义分配存储或给出函数体。非 `inline` 的变量与函数一个程序只能定义一次;`inline` 函数/变量与模板可以出现在多个翻译单元,但定义必须一致。头文件只放声明,定义放 `.cpp`,例外是 `inline` 与模板。
8
+ - 引用是已有对象的别名,必须初始化,不能重新绑定;指针可以为空,也可以改指向。接口优先用引用表达“必须存在”,用指针表达“可以不存在”。
9
+ - `*this` 不用于复制当前对象:要一份副本就直说语义(如“推演落子”只读原数据,或显式写一个复制函数)。`return *this` 仍只属于赋值运算符,井字棋没有这种运算符。
10
+
11
+ ## 依据
12
+
13
+ - [ISO C++ `[basic.def.odr]`](https://eel.is/c++draft/basic.def.odr):一个实体允许的声明与定义次数,以及 ODR 的一致要求。
14
+ - [cppreference: Definitions and ODR](https://en.cppreference.com/w/cpp/language/definition):声明、定义、`inline` 与模板的多翻译单元规则。
15
+ - [C++ Core Guidelines: P.1](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-philosophy):用类型与对象表达意图,不靠注释补语义。
@@ -0,0 +1,26 @@
1
+ # 初始化与列表初始化
2
+
3
+ 默认用花括号初始化,只在需要拷贝初始化或 `auto` 推导时用 `=`;`name = {{` 只用于多行聚合常量表:
4
+
5
+ ```cpp
6
+ int count{}; // 值初始化,0
7
+ std::vector<int> values{1, 2, 3}; // 列表初始化
8
+ std::string name = "demo"; // 拷贝初始化,类型明确
9
+ auto total = 0.0; // 本工作流统一用 = 推导
10
+ ```
11
+
12
+ - `kLines` 这类多行聚合常量表写 `name = {{`;单个对象和空初始化仍写 `count{}`,不写 `=`;不把其他花括号初始化改成 `=`。
13
+ - `T value{}` 做值初始化:内置类型得 0,类类型调用默认构造函数。
14
+ - `auto x{1}` 在 C++17 起合法,但 `{}` 与 `initializer_list` 的重载容易误读;本工作流统一写 `auto x = 1`。
15
+ - 花括号禁止窄化转换:`int x{3.5}` 编译失败,`int x = 3.5` 静默截断。需要截断时显式 `static_cast<int>(3.5)`。
16
+ - `std::vector<int> values(3)` 是三个 0;`values{3}` 是一个元素 3。两种括号语义不同,不要凭习惯混用。
17
+ - 类成员在声明处写默认成员初始化(NSDMI),一律用花括号:标量 `count_{0}`,数组 `items_{}`,容器与类类型成员写空 `{}`(如 `std::vector<int> values_{};`、`Board board_{};`)。
18
+ - `=` 只用于花括号不可用或会改变含义的例外:引用成员不写 NSDMI,在构造函数初始化列表绑定;容器需要 `std::vector<int>(n)` 的容量构造时写 `= std::vector<int>(n)`,或在构造函数初始化列表写 `v_(n)`;`std::initializer_list` 成员避免使用,确实需要时写 `= {..}` 并保证底层数组的生命周期长于对象;花括号无法构造的类型才回退到 `= value` 或构造函数初始化列表。`=` 仍然是初始化,不是赋值。
19
+ - `static` 与 `static constexpr` 数据成员不是对象成员,继续写 `= 3`;`auto` 不能做非静态数据成员。
20
+ - 构造函数初始化列表按成员声明顺序执行,不按书写顺序;初始化列表顺序与声明顺序保持一致,避免依赖未初始化成员。
21
+
22
+ ## 依据
23
+
24
+ - [ISO C++ `[dcl.init]`](https://eel.is/c++draft/dcl.init):值初始化、列表初始化、拷贝初始化与窄化转换。
25
+ - [cppreference: Initialization](https://en.cppreference.com/w/cpp/language/initialization):各种初始化语法与重载选择。
26
+ - [C++ Core Guidelines: ES.23](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#res-list):优先 `{}` 初始化;本工作流按此执行,并只为拷贝/`auto` 保留 `=`。
@@ -0,0 +1,12 @@
1
+ # `auto` 与类型推导
2
+
3
+ - `auto` 适合“右侧类型显然且无关紧要”的局部变量,例如迭代器、`make_unique` 结果、范围 `for`。
4
+ - 公共接口、类成员、函数返回类型写显式类型;返回值需要隐藏实现细节时才可以写 `auto`,且头文件里要能看出契约。
5
+ - `auto` 会丢掉顶层 `const` 和引用:`auto value = const_ref` 得到副本;需要引用时写 `const auto&`。
6
+ - 结构化绑定 `auto [key, value] : map` 中,`key` 是副本;要避免复制时写 `const auto& [key, value]`。
7
+
8
+ ## 依据
9
+
10
+ - [ISO C++ `[dcl.spec.auto]`](https://eel.is/c++draft/dcl.spec.auto):`auto` 的推导规则与占位符约束。
11
+ - [cppreference: `auto`](https://en.cppreference.com/w/cpp/language/auto):顶层 `const`/引用丢失、`decltype(auto)` 与结构化绑定。
12
+ - [Google C++ Style Guide: `auto`](https://google.github.io/styleguide/cppguide.html#auto):只在类型显然的局部变量使用,公共接口写显式类型。
@@ -0,0 +1,25 @@
1
+ # `const`、`constexpr`、`consteval`、`constinit`
2
+
3
+ | 关键字 | 承诺 | 典型位置 |
4
+ | --- | --- | --- |
5
+ | `const` | 初始化后不能通过这个名字修改 | 局部变量、参数、成员函数尾部 |
6
+ | `constexpr` | 能在编译期求值(满足条件时) | 常量、函数、构造函数 |
7
+ | `consteval` | 必须在编译期求值 | 编译期校验函数 |
8
+ | `constinit` | 静态存储期变量在编译期完成初始化 | 全局/静态变量 |
9
+ | `inline constexpr` | 头文件里可共享的编译期常量,避免 ODR 问题 | 命名空间作用域常量 |
10
+
11
+ - 共享常量写在头文件的命名空间作用域:`inline constexpr int kMaxRows = 3;`,不要用 `#define`。`.cpp` 里非 `inline`、非 `extern` 的命名空间作用域 `constexpr` 已有内部链接。
12
+ - `constexpr` 函数的定义要放在头文件里,否则其他翻译单元无法在编译期调用。
13
+ - 不要给所有函数加 `constexpr`;只有确实需要在编译期使用、且实现满足约束时才加。
14
+ - `constinit` 只保证初始化时机,不保证不可修改;需要不可修改时同时写 `const`。
15
+ - C++20 起 `constexpr` 函数可以包含循环、局部变量和部分动态分配,但不要借此把运行期逻辑塞进编译期。
16
+ - 局部变量默认不加 `const`:短生命周期的局部值只读一次,`const` 不改变存储与运行行为。把 `const` 留给接口契约——`const` 引用参数、`const` 成员函数、指向只读数据的指针与视图,以及确实要防止后续误写的变量。Core Guidelines 的 Con.1 主张默认不可变;本仓取 Google 风格的做法,只在接口层要求 `const`。
17
+
18
+ ## 依据
19
+
20
+ - [ISO C++ `[dcl.constexpr]`](https://eel.is/c++draft/dcl.constexpr):`constexpr`、`consteval` 的求值时机与函数约束。
21
+ - [cppreference: `constexpr`](https://en.cppreference.com/w/cpp/language/constexpr):常量表达式、`constinit` 与 `consteval` 的对照。
22
+ - [cppreference: `constinit`](https://en.cppreference.com/w/cpp/language/constinit):静态存储期初始化时机,不改变可修改性。
23
+ - [Google C++ Style Guide: Use of const](https://google.github.io/styleguide/cppguide.html#Use_of_const):「We strongly recommend using `const` in APIs (i.e., on function parameters, methods, and non-local variables) wherever it is meaningful and accurate.」局部变量不在要求之内。
24
+ - [Chromium C++ style](https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/c++.md) 与 [LLVM Coding Standards](https://llvm.org/docs/CodingStandards.html):同样没有要求局部变量加 `const`;LLVM 只对静态与全局常量用 `constexpr`。
25
+ - [C++ Core Guidelines: Con.1](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#rconst-immutable):主张默认不可变;本仓只在接口处采用这一主张,局部变量按上一条处理。
@@ -0,0 +1,23 @@
1
+ # 表达式与比较
2
+
3
+ - 比较写成“变量在左、常量在右”:`if (id < kTaskCount)`,不写 Yoda 条件 `if (kTaskCount > id)`;常量与枚举值总在右边。成员与参数比较时,成员状态在左、参数在右,如 `if (current_player_ != move.player)`:判断「轮到谁」以对象自己的状态为起点,参数是被核对的一次输入;成员与常量比较时成员在左,如 `if (value_ != SquareValue::kEmpty)`;参数与常量比较时参数在左。分不清主次时按“读起来的主语”决定,同一段代码保持同一种顺序。
4
+ - 同一个值对多个离散取值分派时用 `switch`,不用一串 `if`:值来自枚举或整数常量、分支 3 个以上、分支体短。枚举覆盖全部取值时不写 `default`,新增取值由 `-Wswitch` 指出;编译器需要出口时在 `switch` 后写 `std::unreachable()`,不写 `throw` 兜底。
5
+ - 条件是比较范围、布尔组合,或只有 1–2 个分支,或「失败提前返回、成功落到末尾」的守卫时用 `if`,末尾直接写成功路径。
6
+ - 不依赖隐式穿透;确实需要穿透时写 `[[fallthrough]]`。
7
+ - 混合优先级的算术表达式加括号:`(a + b) * c`,不依赖读者记忆优先级。`readability-math-missing-parentheses` 会检查。
8
+ - 区间用半开区间 `[low, high)`;判空用 `empty()`,不要用 `size() == 0`。
9
+ - 逻辑表达式按语义分组,一组一个括号;组内的单个比较不再加括号,`&&` 的优先级已经清楚,多加一层反而难核对。
10
+ - 整行在列宽内时写一行;放不下时按组换行,各组对齐。不要把多个否定串成一行。
11
+ - 自增自减单独成句;不要在同一个表达式里对同一对象多次修改,那是未定义行为。
12
+
13
+ ## 依据
14
+
15
+ - [ISO C++ `[expr]`](https://eel.is/c++draft/expr):运算符优先级、求值顺序与未定义行为。
16
+ - [cppreference: Expressions](https://en.cppreference.com/w/cpp/language/expressions):运算符分类、短路与序列点规则。
17
+ - [C++ Core Guidelines: ES.41](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-expr):避免容易误读的表达式,必要时加括号。
18
+ - [Style Guide for Writing Comparisons in Conditions](https://www.enyo.de/fw/notes/style-guide-conditions.html):变化最快、最不确定的一方写在比较左边;常量前置已无必要,且常掩盖本意。
19
+ - [clang-tidy `readability-constant-operand-order`](https://github.com/llvm/llvm-project/pull/167158):现代代码库倾向统一写 `x == 0`,不写 `0 == x`。
20
+ - [LLVM Coding Standards](https://llvm.org/docs/CodingStandards.html) 与 [Linux kernel coding style](https://www.kernel.org/doc/html/latest/process/coding-style.html):示例都用自然语序(`I != E`、`system_state == SYSTEM_RUNNING`),不把常量前置。
21
+ - [C++ Core Guidelines: ES.70、ES.78、ES.79](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-expr):有选择时优先 `switch`;对常量比较,通常比 `if`-`then`-`else` 链更容易优化,并能提示枚举是否覆盖全;不依赖隐式穿透,`default` 只处理常见情况。
22
+ - [LLVM Coding Standards: Don't use default labels in fully covered switches over enumerations](https://llvm.org/docs/CodingStandards.html#don-t-use-default-labels-in-fully-covered-switches-over-enumerations):全覆盖枚举 `switch` 不写 `default`;需要给编译器出口时在 `switch` 后用 `llvm_unreachable`(对应本项目的 `std::unreachable`)。
23
+ - [Google C++ Style Guide: switch statements](https://google.github.io/styleguide/cppguide.html#switch-statements):非枚举条件的 `switch` 必须有 `default`;枚举由编译器提醒未覆盖值;`[[fallthrough]]` 必须标注。
@@ -0,0 +1,15 @@
1
+ # 函数、参数与返回值
2
+
3
+ - 命名规则以 `references/naming/identifier-names.md` 为准:函数 PascalCase、查询 `Is` / `Has` / `Can` / `Get` / `Find`、转换 `SourceToTarget`。
4
+ - 输入参数默认按值传小对象、按 `const&` 传大对象;需要修改调用方对象时用引用参数,并在名字或注释里标 `[out]`。
5
+ - 优先返回值而不是输出参数;需要返回多个值时用 `struct` 聚合,不用多个 `bool` 输出参数。
6
+ - 返回容器或大对象时按值返回,依赖 RVO / 移动;不要返回局部对象的引用或指针。
7
+ - 单参数构造函数加 `explicit`,除非确实需要隐式转换;转换运算符也加 `explicit`。
8
+ - 不在虚函数上写默认参数;默认参数在静态类型处绑定,派生类改默认值会造成意外。
9
+ - 函数只做一件事;超过一屏时先找可命名的子步骤,分阶段与注释写法见 `steps/04-implementation.md`。
10
+
11
+ ## 依据
12
+
13
+ - [ISO C++ `[dcl.fct]`](https://eel.is/c++draft/dcl.fct):函数声明、参数与返回类型。
14
+ - [cppreference: Functions](https://en.cppreference.com/w/cpp/language/functions):重载、默认参数与返回类型推导。
15
+ - [Google C++ Style Guide: Functions](https://google.github.io/styleguide/cppguide.html#Functions):短小、单一职责,参数与返回值写清契约。
@@ -0,0 +1,15 @@
1
+ # 类、结构体与特殊成员
2
+
3
+ - `struct` 用于公开数据的聚合;`class` 用于维护不变量、隐藏表示。两者只差默认访问权限,按语义选。
4
+ - 数据成员默认私有;需要暴露只读视图时提供 `const` 成员函数,不返回可变内部引用。
5
+ - 单参数构造函数用 `explicit`;构造函数失败时抛异常,不留下半初始化对象。
6
+ - 特殊成员(构造、析构、拷贝、移动)在头文件声明,在 `.cpp` 定义;只有默认实现足够时才写 `= default`,默认构造要无参数,拷贝/移动构造按各自的签名。
7
+ - 定义了析构函数、拷贝构造或拷贝赋值之一时,认真考虑其余特殊成员;用 `= delete` 明确禁止不需要的操作。
8
+ - 多态基类析构函数必须是 `virtual` 或 `protected`;否则通过基类指针删除派生对象是未定义行为。
9
+ - 不在构造函数里调用虚函数;此时派生部分还没构造完。
10
+
11
+ ## 依据
12
+
13
+ - [ISO C++ `[class]`](https://eel.is/c++draft/class):类成员、访问控制与特殊成员的声明规则。
14
+ - [cppreference: Classes](https://en.cppreference.com/w/cpp/language/classes):构造/析构、拷贝/移动与 `= default`/`= delete`。
15
+ - [Google C++ Style Guide: Classes](https://google.github.io/styleguide/cppguide.html#Classes):struct 与 class 的分工、显式构造函数与虚析构。
@@ -0,0 +1,15 @@
1
+ # RAII、所有权与移动
2
+
3
+ - 资源获取即初始化:用对象生存期管理内存、文件、锁、套接字;析构函数负责释放。
4
+ - 默认用 `std::unique_ptr<T>` 表达独占所有权;需要共享所有权时才用 `std::shared_ptr<T>`,并用 `std::weak_ptr` 打破循环。
5
+ - 不写裸 `new` / `delete`;需要动态数组时用 `std::vector`,需要单个对象时用 `std::make_unique`。
6
+ - 移动把资源从源对象转走;`std::move` 只是 `static_cast<T&&>`,本身不移动任何东西。标准只保证移动后的对象处于有效但未指定状态,智能指针通常为空,但不要依赖具体值。
7
+ - 移动后的对象只能重新赋值或销毁,不要读取它的值。
8
+ - 移动构造函数和移动赋值标记 `noexcept`,否则 `std::vector` 等容器在扩容时可能选择拷贝。
9
+ - 返回值直接 `return value;`,不要 `return std::move(value);`;后者阻止 RVO。
10
+
11
+ ## 依据
12
+
13
+ - [ISO C++ `[class.copy.ctor]`](https://eel.is/c++draft/class.copy.ctor):移动构造与移动赋值的语义、`noexcept` 与隐式生成。
14
+ - [cppreference: RAII](https://en.cppreference.com/w/cpp/language/raii):资源生存期与异常安全。
15
+ - [C++ Core Guidelines: R.1](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-resource):用 RAII 管理资源,避免裸 `new`/`delete`。
@@ -0,0 +1,26 @@
1
+ # 模板、概念与 CTAD
2
+
3
+ - 模板定义放头文件;`.cpp` 里的模板实例化只对当前翻译单元可见。
4
+ - C++20 用概念约束模板参数,把错误从实例化深处提前到调用点:
5
+
6
+ ```cpp
7
+ template <typename T>
8
+ concept Numeric = std::is_arithmetic_v<T>;
9
+
10
+ template <Numeric T>
11
+ T Clamp(T value, T low, T high) {
12
+ if (value < low) return low;
13
+ if (value > high) return high;
14
+ return value;
15
+ }
16
+ ```
17
+
18
+ - 概念只表达语法和语义约束,不替代文档;错误消息要能让调用者知道违反了哪条约束。
19
+ - CTAD(类模板实参推导)用于局部变量和明显场景:`std::pair pair{1, 2.0};`;公共接口写显式模板实参,避免推导规则变化影响契约。
20
+ - 不用模板做运行期分支;需要运行期多态时用虚函数或 `std::variant`。
21
+
22
+ ## 依据
23
+
24
+ - [ISO C++ `[temp]`](https://eel.is/c++draft/temp):模板定义、实例化与两阶段名字查找。
25
+ - [cppreference: Templates](https://en.cppreference.com/w/cpp/language/templates):模板参数、特化与依赖名。
26
+ - [cppreference: Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints):概念、`requires` 与约束归约。
@@ -0,0 +1,10 @@
1
+ # 检查清单
2
+
3
+ - [ ] 初始化方式统一,窄化转换被编译器拦住。
4
+ - [ ] `auto` 只出现在类型显然的局部变量;公共接口有显式类型。
5
+ - [ ] 共享常量用 `inline constexpr`,没有宏常量。
6
+ - [ ] 局部变量不加 `const`;`const` 用在参数、成员函数与只读视图上。
7
+ - [ ] 比较不是 Yoda 形式;成员与参数比较时成员状态在左、参数在右;混合优先级有括号。
8
+ - [ ] 资源由 RAII 管理,没有裸 `new` / `delete`。
9
+ - [ ] 特殊成员声明与定义位置正确,移动操作 `noexcept`。
10
+ - [ ] 模板约束用概念表达,定义在头文件。
@@ -0,0 +1,22 @@
1
+ # 测量顺序
2
+
3
+ 先证明慢在哪里,再改代码。没有测量的“优化”通常只是把复杂度搬了个位置。
4
+
5
+ 本组条文只管性能判断与测量;语言规则见 `references/language/language-basics/01-objects.md`,容器与算法选择见 `references/language/standard-library/01-containers.md`,静态检查开关见 `engineering` 的 `references/formatting/03-clang-tidy.md`。
6
+
7
+ 1. 写清可观察的性能目标:延迟、吞吐、内存上限,或“输入规模翻倍时耗时如何增长”。
8
+ 2. 用真实规模的输入测量;玩具数据上的常数差异没有意义。
9
+ 3. 先看算法复杂度,再看内存访问,再看常数因子。
10
+ 4. 用 profiler 找热点;不要凭代码长短猜。
11
+ 5. 改一处,复测同一指标;记录测量条件和结果。
12
+
13
+ - 发布构建(`-O2` / `-O3`)测性能,调试构建测正确性。
14
+ - 微基准要防止编译器把结果优化掉;使用输入、累加结果并输出。
15
+ - 单次测量受缓存、频率、调度影响;取多次的中位数或分位数,不只报最好的一次。
16
+ - 采样 profiler(Linux `perf record`、macOS Instruments、Windows ETW)给出热点分布;调用次数与单次耗时一起看,避免被高频小函数带偏。
17
+
18
+ ## 依据
19
+
20
+ - [ISO C++ `[intro.abstract]`](https://eel.is/c++draft/intro.abstract):as-if 规则允许编译器重排,性能结论只能来自测量。
21
+ - [C++ Core Guidelines: Per.1](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):没有理由不要优化;先测量再改。
22
+ - [C++ Core Guidelines: Per.6](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):没有测量就没有性能结论。
@@ -0,0 +1,13 @@
1
+ # 复杂度与数据结构
2
+
3
+ - 先问操作的渐进复杂度:`vector` 尾部追加摊还 O(1),中间插入 O(n);`map` 查找 O(log n);`unordered_map` 平均 O(1)、最坏 O(n)。
4
+ - 嵌套循环里做线性查找通常是把 O(n) 变成 O(n²);先建索引或排序。
5
+ - 频繁按 key 查找时,`unordered_map` 通常比 `map` 快,但迭代顺序不稳定;需要有序输出时不要选它。
6
+ - 小规模数据(几十个元素)上,连续 `vector` 的线性扫描常比哈希表更快;不要机械套用复杂度。
7
+ - 递归深度可能随输入增长时,改成迭代或显式栈;栈溢出不是可捕获的异常。
8
+
9
+ ## 依据
10
+
11
+ - [ISO C++ `[container.requirements]`](https://eel.is/c++draft/container.requirements):各容器的复杂度保证。
12
+ - [cppreference: Containers library](https://en.cppreference.com/w/cpp/container):查找、插入、遍历的复杂度对照。
13
+ - [C++ Core Guidelines: Per.4](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):理解算法与数据结构的成本,再谈常数因子。
@@ -0,0 +1,14 @@
1
+ # 内存与缓存
2
+
3
+ - 连续存储对缓存友好;`vector<struct>` 比 `vector<unique_ptr<struct>>` 更容易预取。
4
+ - 只遍历部分字段时,AoS(数组的结构)可能浪费带宽;数据量大且按列访问时考虑 SoA(结构的数组),但先用 profiler 证明。
5
+ - 小对象按值传递通常比堆分配快;不要为了“避免拷贝”给所有参数加指针。
6
+ - `reserve` 减少 `vector` 扩容和搬移;只有已知上界或能准确估算时才用。`reserve` 只改容量、不改 size;`shrink_to_fit` 不保证真正释放。
7
+ - 移动大对象比拷贝便宜,但移动不是免费;不要把 `std::move` 当成优化开关。
8
+ - 返回局部对象直接 `return value;`,依赖 RVO / NRVO;`return std::move(value);` 会阻止优化。
9
+
10
+ ## 依据
11
+
12
+ - [ISO C++ `[vector]`](https://eel.is/c++draft/vector):容量、扩容与 `reserve` 的保证。
13
+ - [cppreference: `std::vector`](https://en.cppreference.com/w/cpp/container/vector):容量接口与迭代器失效。
14
+ - [C++ Core Guidelines: Per.16](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):用紧凑的连续数据结构提升缓存命中。
@@ -0,0 +1,28 @@
1
+ # 未定义行为与安全
2
+
3
+ 以下行为没有标准结果,优化后可能表现为“有时对”;编译器可以假设它们不发生,把整段分支删掉。
4
+
5
+ - 数组/容器越界访问(`operator[]`、指针算术)。
6
+ - 解引用空指针或已释放对象(use-after-free、double free)。
7
+ - 读取未初始化变量。
8
+ - 有符号整数溢出。
9
+ - 数据竞争:多个线程无同步地读写同一对象。
10
+ - 用 `reinterpret_cast` 把对象当无关类型访问,违反严格别名规则。
11
+ - 对象生存期结束后继续使用指针或引用。
12
+
13
+ 工具:
14
+
15
+ - AddressSanitizer(ASan)查越界、use-after-free、double free。
16
+ - UndefinedBehaviorSanitizer(UBSan)查有符号溢出、空指针、对齐等问题。
17
+ - ThreadSanitizer(TSan)查数据竞争。
18
+ - `-Wall -Wextra -Wpedantic` 打开常用警告;不要靠关闭警告“修复”问题。
19
+
20
+ ASan/UBSan 有运行期开销,只在测试和排查时开;发布构建仍要保留编译器警告。
21
+
22
+ ## 依据
23
+
24
+ - [ISO C++ `[intro.abstract]`](https://eel.is/c++draft/intro.abstract):编译器只需模拟可观察行为,UB 不受约束。
25
+ - [cppreference: Undefined behavior](https://en.cppreference.com/w/cpp/language/ub):常见 UB 与优化后果。
26
+ - [Clang AddressSanitizer](https://clang.llvm.org/docs/AddressSanitizer.html):越界、use-after-free、double free 的检测。
27
+ - [Clang UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html):有符号溢出、空指针、对齐等检查。
28
+ - [Clang ThreadSanitizer](https://clang.llvm.org/docs/ThreadSanitizer.html):数据竞争检测。
@@ -0,0 +1,17 @@
1
+ # 常见性能陷阱
2
+
3
+ | 现象 | 常见原因 | 先做什么 |
4
+ | --- | --- | --- |
5
+ | 循环里反复分配 | 每次迭代构造容器/字符串 | 移到循环外,或 `reserve` |
6
+ | 大量拷贝 | 范围 `for` 按值、参数按值传大对象 | 改 `const&`,确认所有权 |
7
+ | 哈希表慢 | 哈希冲突、频繁 rehash | 预留桶数,检查哈希质量 |
8
+ | 字符串拼接慢 | 反复 `+` 产生临时对象 | `reserve` + `+=`,或 `std::format` 一次成型 |
9
+ | 多线程没有变快 | 锁竞争、伪共享 | 缩小临界区,按缓存行对齐 |
10
+ | 递归慢/栈溢出 | 重复子问题、深度大 | 记忆化或改迭代 |
11
+ | 输出慢 | 每行 flush、频繁 `std::endl` | 用 `'\n'`,需要时再 flush |
12
+
13
+ ## 依据
14
+
15
+ - [C++ Core Guidelines: Per.14](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):减少不必要的分配与释放。
16
+ - [C++ Core Guidelines: Per.15](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):不要在关键路径里分配。
17
+ - [cppreference: `std::vector`](https://en.cppreference.com/w/cpp/container/vector):扩容、`reserve` 与引用失效。
@@ -0,0 +1,13 @@
1
+ # 不要做的“优化”
2
+
3
+ - 不要用全局可变状态换速度;正确性和可测试性先于常数因子。
4
+ - 不要为未测量的热点写复杂的手工内存管理。
5
+ - 不要用 `reinterpret_cast` 绕过类型系统;需要二进制布局时用 `std::bit_cast` 并确认可平凡复制。
6
+ - 不要把 `std::endl` 当换行符;它每次都会 flush。
7
+ - 不要用 `-ffast-math` 换浮点速度;它改变 NaN、Inf 和结合律语义,`std::isfinite` 等判断会失真。
8
+
9
+ ## 依据
10
+
11
+ - [C++ Core Guidelines: Per.2](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):不要过早优化。
12
+ - [C++ Core Guidelines: Per.3](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#s-performance):不要优化不重要的部分。
13
+ - [cppreference: `std::bit_cast`](https://en.cppreference.com/w/cpp/numeric/bit_cast):要求可平凡复制且大小相同,不是任意类型双关。