pi-usereq 0.4.0

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 (361) hide show
  1. package/.g.conf +20 -0
  2. package/.github/workflows/release-npm.yml +131 -0
  3. package/.gitignore +270 -0
  4. package/CHANGELOG.md +221 -0
  5. package/LICENSE +674 -0
  6. package/README.md +260 -0
  7. package/TODO.md +20 -0
  8. package/docs/pi.dev/agent-document-manifest.json +6399 -0
  9. package/docs/pi.dev/coding-agent-docs/compaction.md +394 -0
  10. package/docs/pi.dev/coding-agent-docs/custom-provider.md +596 -0
  11. package/docs/pi.dev/coding-agent-docs/development.md +71 -0
  12. package/docs/pi.dev/coding-agent-docs/extensions.md +2262 -0
  13. package/docs/pi.dev/coding-agent-docs/images/doom-extension.png +0 -0
  14. package/docs/pi.dev/coding-agent-docs/images/exy.png +0 -0
  15. package/docs/pi.dev/coding-agent-docs/images/interactive-mode.png +0 -0
  16. package/docs/pi.dev/coding-agent-docs/images/tree-view.png +0 -0
  17. package/docs/pi.dev/coding-agent-docs/json.md +82 -0
  18. package/docs/pi.dev/coding-agent-docs/keybindings.md +175 -0
  19. package/docs/pi.dev/coding-agent-docs/models.md +392 -0
  20. package/docs/pi.dev/coding-agent-docs/packages.md +218 -0
  21. package/docs/pi.dev/coding-agent-docs/prompt-templates.md +67 -0
  22. package/docs/pi.dev/coding-agent-docs/providers.md +195 -0
  23. package/docs/pi.dev/coding-agent-docs/rpc.md +1377 -0
  24. package/docs/pi.dev/coding-agent-docs/sdk.md +1124 -0
  25. package/docs/pi.dev/coding-agent-docs/session.md +412 -0
  26. package/docs/pi.dev/coding-agent-docs/settings.md +247 -0
  27. package/docs/pi.dev/coding-agent-docs/shell-aliases.md +13 -0
  28. package/docs/pi.dev/coding-agent-docs/skills.md +232 -0
  29. package/docs/pi.dev/coding-agent-docs/terminal-setup.md +106 -0
  30. package/docs/pi.dev/coding-agent-docs/termux.md +127 -0
  31. package/docs/pi.dev/coding-agent-docs/themes.md +295 -0
  32. package/docs/pi.dev/coding-agent-docs/tmux.md +61 -0
  33. package/docs/pi.dev/coding-agent-docs/tree.md +231 -0
  34. package/docs/pi.dev/coding-agent-docs/tui.md +887 -0
  35. package/docs/pi.dev/coding-agent-docs/windows.md +17 -0
  36. package/docs/pi.dev/mom-docs/artifacts-server.md +475 -0
  37. package/docs/pi.dev/mom-docs/events.md +307 -0
  38. package/docs/pi.dev/mom-docs/new.md +970 -0
  39. package/docs/pi.dev/mom-docs/sandbox.md +153 -0
  40. package/docs/pi.dev/mom-docs/slack-bot-minimal-guide.md +399 -0
  41. package/docs/pi.dev/mom-docs/v86.md +319 -0
  42. package/docs/pi.dev/pods-docs/gml-4.5.md +189 -0
  43. package/docs/pi.dev/pods-docs/gpt-oss.md +233 -0
  44. package/docs/pi.dev/pods-docs/implementation-plan.md +183 -0
  45. package/docs/pi.dev/pods-docs/kimi-k2.md +197 -0
  46. package/docs/pi.dev/pods-docs/models.md +116 -0
  47. package/docs/pi.dev/pods-docs/plan.md +166 -0
  48. package/docs/pi.dev/pods-docs/qwen3-coder.md +132 -0
  49. package/images/flowchart-bw.png +0 -0
  50. package/images/flowchart-bw.svg +102 -0
  51. package/images/flowchart.md +100 -0
  52. package/images/flowchart.png +0 -0
  53. package/images/flowchart.svg +3 -0
  54. package/package.json +46 -0
  55. package/req/docs/REFERENCES.md +4554 -0
  56. package/req/docs/REQUIREMENTS.md +475 -0
  57. package/req/docs/WORKFLOW.md +1059 -0
  58. package/scripts/debug-extension.ts +497 -0
  59. package/scripts/lib/extension-debug-harness.ts +450 -0
  60. package/scripts/lib/recording-extension-api.ts +786 -0
  61. package/scripts/lib/sdk-smoke.ts +503 -0
  62. package/scripts/pi-usereq-debug.sh +330 -0
  63. package/scripts/tool-args-to-params.ts +208 -0
  64. package/src/cli.ts +349 -0
  65. package/src/core/agent-tool-json.ts +621 -0
  66. package/src/core/compress-files.ts +72 -0
  67. package/src/core/compress-payload.ts +648 -0
  68. package/src/core/compress.ts +464 -0
  69. package/src/core/config.ts +272 -0
  70. package/src/core/doxygen-parser.ts +318 -0
  71. package/src/core/errors.ts +31 -0
  72. package/src/core/extension-status.ts +660 -0
  73. package/src/core/find-constructs.ts +319 -0
  74. package/src/core/find-payload.ts +915 -0
  75. package/src/core/generate-markdown.ts +120 -0
  76. package/src/core/path-context.ts +196 -0
  77. package/src/core/pi-notify.ts +430 -0
  78. package/src/core/pi-usereq-tools.ts +140 -0
  79. package/src/core/prompts.ts +184 -0
  80. package/src/core/reference-payload.ts +818 -0
  81. package/src/core/resources.ts +63 -0
  82. package/src/core/runtime-project-paths.ts +99 -0
  83. package/src/core/settings-menu.ts +233 -0
  84. package/src/core/source-analyzer.ts +1721 -0
  85. package/src/core/static-check.ts +674 -0
  86. package/src/core/token-counter.ts +729 -0
  87. package/src/core/tool-runner.ts +717 -0
  88. package/src/core/utils.ts +185 -0
  89. package/src/index.ts +2209 -0
  90. package/src/resources/guidelines/Google_C++_Style_Guide.md +3711 -0
  91. package/src/resources/guidelines/Google_Python_Style_Guide.md +3709 -0
  92. package/src/resources/prompts/analyze.md +130 -0
  93. package/src/resources/prompts/change.md +227 -0
  94. package/src/resources/prompts/check.md +139 -0
  95. package/src/resources/prompts/cover.md +219 -0
  96. package/src/resources/prompts/create.md +104 -0
  97. package/src/resources/prompts/fix.md +221 -0
  98. package/src/resources/prompts/flowchart.md +220 -0
  99. package/src/resources/prompts/implement.md +163 -0
  100. package/src/resources/prompts/new.md +226 -0
  101. package/src/resources/prompts/readme.md +182 -0
  102. package/src/resources/prompts/recreate.md +213 -0
  103. package/src/resources/prompts/refactor.md +213 -0
  104. package/src/resources/prompts/references.md +100 -0
  105. package/src/resources/prompts/renumber.md +119 -0
  106. package/src/resources/prompts/workflow.md +202 -0
  107. package/src/resources/prompts/write.md +99 -0
  108. package/src/resources/sounds/Machine-alert-beep-sound-effect.mp3 +0 -0
  109. package/src/resources/sounds/Soft-high-tech-notification-sound-effect.mp3 +0 -0
  110. package/src/resources/templates/Document_Source_Code_in_Doxygen_Style.md +130 -0
  111. package/src/resources/templates/HDT_Test_Authoring_Guide.md +318 -0
  112. package/src/resources/templates/Requirements_Template.md +78 -0
  113. package/tests/attended-results-scenarios.ts +758 -0
  114. package/tests/attended-results.test.ts +39 -0
  115. package/tests/cli-command-option-parity.test.ts +815 -0
  116. package/tests/debug-extension-harness.test.ts +463 -0
  117. package/tests/extension-registration.test.ts +2006 -0
  118. package/tests/fixtures/fixture_c.c +361 -0
  119. package/tests/fixtures/fixture_cpp.cpp +407 -0
  120. package/tests/fixtures/fixture_csharp.cs +411 -0
  121. package/tests/fixtures/fixture_elixir.ex +409 -0
  122. package/tests/fixtures/fixture_go.go +341 -0
  123. package/tests/fixtures/fixture_haskell.hs +250 -0
  124. package/tests/fixtures/fixture_java.java +430 -0
  125. package/tests/fixtures/fixture_javascript.js +383 -0
  126. package/tests/fixtures/fixture_kotlin.kt +451 -0
  127. package/tests/fixtures/fixture_lua.lua +276 -0
  128. package/tests/fixtures/fixture_perl.pl +310 -0
  129. package/tests/fixtures/fixture_php.php +433 -0
  130. package/tests/fixtures/fixture_python.py +502 -0
  131. package/tests/fixtures/fixture_ruby.rb +345 -0
  132. package/tests/fixtures/fixture_rust.rs +380 -0
  133. package/tests/fixtures/fixture_scala.scala +398 -0
  134. package/tests/fixtures/fixture_shell.sh +276 -0
  135. package/tests/fixtures/fixture_swift.swift +397 -0
  136. package/tests/fixtures/fixture_typescript.ts +434 -0
  137. package/tests/fixtures/fixture_zig.zig +295 -0
  138. package/tests/fixtures_attended_results/project/compress-line-numbers.json +5 -0
  139. package/tests/fixtures_attended_results/project/compress.json +5 -0
  140. package/tests/fixtures_attended_results/project/enable-static-check-invalid-command.json +5 -0
  141. package/tests/fixtures_attended_results/project/enable-static-check-valid.json +5 -0
  142. package/tests/fixtures_attended_results/project/files-static-check.json +5 -0
  143. package/tests/fixtures_attended_results/project/find-line-numbers.json +5 -0
  144. package/tests/fixtures_attended_results/project/find.json +5 -0
  145. package/tests/fixtures_attended_results/project/get-base-path.json +5 -0
  146. package/tests/fixtures_attended_results/project/git-check-clean.json +5 -0
  147. package/tests/fixtures_attended_results/project/git-check-dirty.json +5 -0
  148. package/tests/fixtures_attended_results/project/git-path.json +5 -0
  149. package/tests/fixtures_attended_results/project/git-wt-create-invalid.json +5 -0
  150. package/tests/fixtures_attended_results/project/git-wt-create-valid.json +5 -0
  151. package/tests/fixtures_attended_results/project/git-wt-delete-nonexistent.json +5 -0
  152. package/tests/fixtures_attended_results/project/git-wt-delete-valid.json +5 -0
  153. package/tests/fixtures_attended_results/project/git-wt-name.json +5 -0
  154. package/tests/fixtures_attended_results/project/references.json +5 -0
  155. package/tests/fixtures_attended_results/project/static-check.json +5 -0
  156. package/tests/fixtures_attended_results/project/tokens.json +5 -0
  157. package/tests/fixtures_attended_results/standalone/files-compress/fixture_c.c.json +5 -0
  158. package/tests/fixtures_attended_results/standalone/files-compress/fixture_cpp.cpp.json +5 -0
  159. package/tests/fixtures_attended_results/standalone/files-compress/fixture_csharp.cs.json +5 -0
  160. package/tests/fixtures_attended_results/standalone/files-compress/fixture_elixir.ex.json +5 -0
  161. package/tests/fixtures_attended_results/standalone/files-compress/fixture_go.go.json +5 -0
  162. package/tests/fixtures_attended_results/standalone/files-compress/fixture_haskell.hs.json +5 -0
  163. package/tests/fixtures_attended_results/standalone/files-compress/fixture_java.java.json +5 -0
  164. package/tests/fixtures_attended_results/standalone/files-compress/fixture_javascript.js.json +5 -0
  165. package/tests/fixtures_attended_results/standalone/files-compress/fixture_kotlin.kt.json +5 -0
  166. package/tests/fixtures_attended_results/standalone/files-compress/fixture_lua.lua.json +5 -0
  167. package/tests/fixtures_attended_results/standalone/files-compress/fixture_perl.pl.json +5 -0
  168. package/tests/fixtures_attended_results/standalone/files-compress/fixture_php.php.json +5 -0
  169. package/tests/fixtures_attended_results/standalone/files-compress/fixture_python.py.json +5 -0
  170. package/tests/fixtures_attended_results/standalone/files-compress/fixture_ruby.rb.json +5 -0
  171. package/tests/fixtures_attended_results/standalone/files-compress/fixture_rust.rs.json +5 -0
  172. package/tests/fixtures_attended_results/standalone/files-compress/fixture_scala.scala.json +5 -0
  173. package/tests/fixtures_attended_results/standalone/files-compress/fixture_shell.sh.json +5 -0
  174. package/tests/fixtures_attended_results/standalone/files-compress/fixture_swift.swift.json +5 -0
  175. package/tests/fixtures_attended_results/standalone/files-compress/fixture_typescript.ts.json +5 -0
  176. package/tests/fixtures_attended_results/standalone/files-compress/fixture_zig.zig.json +5 -0
  177. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_c.c.json +5 -0
  178. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_cpp.cpp.json +5 -0
  179. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_csharp.cs.json +5 -0
  180. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_elixir.ex.json +5 -0
  181. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_go.go.json +5 -0
  182. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_haskell.hs.json +5 -0
  183. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_java.java.json +5 -0
  184. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_javascript.js.json +5 -0
  185. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_kotlin.kt.json +5 -0
  186. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_lua.lua.json +5 -0
  187. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_perl.pl.json +5 -0
  188. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_php.php.json +5 -0
  189. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_python.py.json +5 -0
  190. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_ruby.rb.json +5 -0
  191. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_rust.rs.json +5 -0
  192. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_scala.scala.json +5 -0
  193. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_shell.sh.json +5 -0
  194. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_swift.swift.json +5 -0
  195. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_typescript.ts.json +5 -0
  196. package/tests/fixtures_attended_results/standalone/files-compress-line-numbers/fixture_zig.zig.json +5 -0
  197. package/tests/fixtures_attended_results/standalone/files-find/fixture_c.c.json +5 -0
  198. package/tests/fixtures_attended_results/standalone/files-find/fixture_cpp.cpp.json +5 -0
  199. package/tests/fixtures_attended_results/standalone/files-find/fixture_csharp.cs.json +5 -0
  200. package/tests/fixtures_attended_results/standalone/files-find/fixture_elixir.ex.json +5 -0
  201. package/tests/fixtures_attended_results/standalone/files-find/fixture_go.go.json +5 -0
  202. package/tests/fixtures_attended_results/standalone/files-find/fixture_haskell.hs.json +5 -0
  203. package/tests/fixtures_attended_results/standalone/files-find/fixture_java.java.json +5 -0
  204. package/tests/fixtures_attended_results/standalone/files-find/fixture_javascript.js.json +5 -0
  205. package/tests/fixtures_attended_results/standalone/files-find/fixture_kotlin.kt.json +5 -0
  206. package/tests/fixtures_attended_results/standalone/files-find/fixture_lua.lua.json +5 -0
  207. package/tests/fixtures_attended_results/standalone/files-find/fixture_perl.pl.json +5 -0
  208. package/tests/fixtures_attended_results/standalone/files-find/fixture_php.php.json +5 -0
  209. package/tests/fixtures_attended_results/standalone/files-find/fixture_python.py.json +5 -0
  210. package/tests/fixtures_attended_results/standalone/files-find/fixture_ruby.rb.json +5 -0
  211. package/tests/fixtures_attended_results/standalone/files-find/fixture_rust.rs.json +5 -0
  212. package/tests/fixtures_attended_results/standalone/files-find/fixture_scala.scala.json +5 -0
  213. package/tests/fixtures_attended_results/standalone/files-find/fixture_shell.sh.json +5 -0
  214. package/tests/fixtures_attended_results/standalone/files-find/fixture_swift.swift.json +5 -0
  215. package/tests/fixtures_attended_results/standalone/files-find/fixture_typescript.ts.json +5 -0
  216. package/tests/fixtures_attended_results/standalone/files-find/fixture_zig.zig.json +5 -0
  217. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_c.c.json +5 -0
  218. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_cpp.cpp.json +5 -0
  219. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_csharp.cs.json +5 -0
  220. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_elixir.ex.json +5 -0
  221. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_go.go.json +5 -0
  222. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_haskell.hs.json +5 -0
  223. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_java.java.json +5 -0
  224. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_javascript.js.json +5 -0
  225. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_kotlin.kt.json +5 -0
  226. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_lua.lua.json +5 -0
  227. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_perl.pl.json +5 -0
  228. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_php.php.json +5 -0
  229. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_python.py.json +5 -0
  230. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_ruby.rb.json +5 -0
  231. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_rust.rs.json +5 -0
  232. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_scala.scala.json +5 -0
  233. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_shell.sh.json +5 -0
  234. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_swift.swift.json +5 -0
  235. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_typescript.ts.json +5 -0
  236. package/tests/fixtures_attended_results/standalone/files-find-line-numbers/fixture_zig.zig.json +5 -0
  237. package/tests/fixtures_attended_results/standalone/files-references/fixture_c.c.json +5 -0
  238. package/tests/fixtures_attended_results/standalone/files-references/fixture_cpp.cpp.json +5 -0
  239. package/tests/fixtures_attended_results/standalone/files-references/fixture_csharp.cs.json +5 -0
  240. package/tests/fixtures_attended_results/standalone/files-references/fixture_elixir.ex.json +5 -0
  241. package/tests/fixtures_attended_results/standalone/files-references/fixture_go.go.json +5 -0
  242. package/tests/fixtures_attended_results/standalone/files-references/fixture_haskell.hs.json +5 -0
  243. package/tests/fixtures_attended_results/standalone/files-references/fixture_java.java.json +5 -0
  244. package/tests/fixtures_attended_results/standalone/files-references/fixture_javascript.js.json +5 -0
  245. package/tests/fixtures_attended_results/standalone/files-references/fixture_kotlin.kt.json +5 -0
  246. package/tests/fixtures_attended_results/standalone/files-references/fixture_lua.lua.json +5 -0
  247. package/tests/fixtures_attended_results/standalone/files-references/fixture_perl.pl.json +5 -0
  248. package/tests/fixtures_attended_results/standalone/files-references/fixture_php.php.json +5 -0
  249. package/tests/fixtures_attended_results/standalone/files-references/fixture_python.py.json +5 -0
  250. package/tests/fixtures_attended_results/standalone/files-references/fixture_ruby.rb.json +5 -0
  251. package/tests/fixtures_attended_results/standalone/files-references/fixture_rust.rs.json +5 -0
  252. package/tests/fixtures_attended_results/standalone/files-references/fixture_scala.scala.json +5 -0
  253. package/tests/fixtures_attended_results/standalone/files-references/fixture_shell.sh.json +5 -0
  254. package/tests/fixtures_attended_results/standalone/files-references/fixture_swift.swift.json +5 -0
  255. package/tests/fixtures_attended_results/standalone/files-references/fixture_typescript.ts.json +5 -0
  256. package/tests/fixtures_attended_results/standalone/files-references/fixture_zig.zig.json +5 -0
  257. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_c.c.json +5 -0
  258. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_cpp.cpp.json +5 -0
  259. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_csharp.cs.json +5 -0
  260. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_elixir.ex.json +5 -0
  261. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_go.go.json +5 -0
  262. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_haskell.hs.json +5 -0
  263. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_java.java.json +5 -0
  264. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_javascript.js.json +5 -0
  265. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_kotlin.kt.json +5 -0
  266. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_lua.lua.json +5 -0
  267. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_perl.pl.json +5 -0
  268. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_php.php.json +5 -0
  269. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_python.py.json +5 -0
  270. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_ruby.rb.json +5 -0
  271. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_rust.rs.json +5 -0
  272. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_scala.scala.json +5 -0
  273. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_shell.sh.json +5 -0
  274. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_swift.swift.json +5 -0
  275. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_typescript.ts.json +5 -0
  276. package/tests/fixtures_attended_results/standalone/files-tokens/fixture_zig.zig.json +5 -0
  277. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_c.c.json +5 -0
  278. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_cpp.cpp.json +5 -0
  279. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_csharp.cs.json +5 -0
  280. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_elixir.ex.json +5 -0
  281. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_go.go.json +5 -0
  282. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_haskell.hs.json +5 -0
  283. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_java.java.json +5 -0
  284. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_javascript.js.json +5 -0
  285. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_kotlin.kt.json +5 -0
  286. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_lua.lua.json +5 -0
  287. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_perl.pl.json +5 -0
  288. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_php.php.json +5 -0
  289. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_python.py.json +5 -0
  290. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_ruby.rb.json +5 -0
  291. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_rust.rs.json +5 -0
  292. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_scala.scala.json +5 -0
  293. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_shell.sh.json +5 -0
  294. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_swift.swift.json +5 -0
  295. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_typescript.ts.json +5 -0
  296. package/tests/fixtures_attended_results/standalone/test-static-check-command/fixture_zig.zig.json +5 -0
  297. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_c.c.json +5 -0
  298. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_cpp.cpp.json +5 -0
  299. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_csharp.cs.json +5 -0
  300. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_elixir.ex.json +5 -0
  301. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_go.go.json +5 -0
  302. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_haskell.hs.json +5 -0
  303. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_java.java.json +5 -0
  304. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_javascript.js.json +5 -0
  305. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_kotlin.kt.json +5 -0
  306. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_lua.lua.json +5 -0
  307. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_perl.pl.json +5 -0
  308. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_php.php.json +5 -0
  309. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_python.py.json +5 -0
  310. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_ruby.rb.json +5 -0
  311. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_rust.rs.json +5 -0
  312. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_scala.scala.json +5 -0
  313. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_shell.sh.json +5 -0
  314. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_swift.swift.json +5 -0
  315. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_typescript.ts.json +5 -0
  316. package/tests/fixtures_attended_results/standalone/test-static-check-dummy/fixture_zig.zig.json +5 -0
  317. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_c.c.json +5 -0
  318. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_cpp.cpp.json +5 -0
  319. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_csharp.cs.json +5 -0
  320. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_elixir.ex.json +5 -0
  321. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_go.go.json +5 -0
  322. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_haskell.hs.json +5 -0
  323. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_java.java.json +5 -0
  324. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_javascript.js.json +5 -0
  325. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_kotlin.kt.json +5 -0
  326. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_lua.lua.json +5 -0
  327. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_perl.pl.json +5 -0
  328. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_php.php.json +5 -0
  329. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_python.py.json +5 -0
  330. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_ruby.rb.json +5 -0
  331. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_rust.rs.json +5 -0
  332. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_scala.scala.json +5 -0
  333. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_shell.sh.json +5 -0
  334. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_swift.swift.json +5 -0
  335. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_typescript.ts.json +5 -0
  336. package/tests/fixtures_attended_results/standalone/test-static-check-pylance/fixture_zig.zig.json +5 -0
  337. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_c.c.json +5 -0
  338. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_cpp.cpp.json +5 -0
  339. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_csharp.cs.json +5 -0
  340. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_elixir.ex.json +5 -0
  341. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_go.go.json +5 -0
  342. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_haskell.hs.json +5 -0
  343. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_java.java.json +5 -0
  344. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_javascript.js.json +5 -0
  345. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_kotlin.kt.json +5 -0
  346. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_lua.lua.json +5 -0
  347. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_perl.pl.json +5 -0
  348. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_php.php.json +5 -0
  349. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_python.py.json +5 -0
  350. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_ruby.rb.json +5 -0
  351. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_rust.rs.json +5 -0
  352. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_scala.scala.json +5 -0
  353. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_shell.sh.json +5 -0
  354. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_swift.swift.json +5 -0
  355. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_typescript.ts.json +5 -0
  356. package/tests/fixtures_attended_results/standalone/test-static-check-ruff/fixture_zig.zig.json +5 -0
  357. package/tests/helpers.ts +204 -0
  358. package/tests/oracle-project.test.ts +63 -0
  359. package/tests/oracle-standalone.test.ts +48 -0
  360. package/tests/prompt-rendering.test.ts +66 -0
  361. package/tests/release-workflow.test.ts +133 -0
@@ -0,0 +1,3711 @@
1
+
2
+ <!-- start of toc -->
3
+
4
+ ** TOC **
5
+ - [C++ Version](#c-version)
6
+ - [Header Files](#header-files)
7
+ - [Self-contained Headers](#self-contained-headers)
8
+ - [The #define Guard](#the-define-guard)
9
+ - [Include What You Use](#include-what-you-use)
10
+ - [Forward Declarations](#forward-declarations)
11
+ - [Defining Functions in Header Files](#defining-functions-in-header-files)
12
+ - [Names and Order of Includes](#names-and-order-of-includes)
13
+ - [Scoping](#scoping)
14
+ - [Namespaces](#namespaces)
15
+ - [Internal Linkage](#internal-linkage)
16
+ - [Nonmember, Static Member, and Global Functions](#nonmember-static-member-and-global-functions)
17
+ - [Local Variables](#local-variables)
18
+ - [Static and Global Variables](#static-and-global-variables)
19
+ - [thread_local Variables](#threadlocal-variables)
20
+ - [Classes](#classes)
21
+ - [Doing Work in Constructors](#doing-work-in-constructors)
22
+ - [Implicit Conversions](#implicit-conversions)
23
+ - [Copyable and Movable Types](#copyable-and-movable-types)
24
+ - [Structs vs. Classes](#structs-vs-classes)
25
+ - [Structs vs. Pairs and Tuples](#structs-vs-pairs-and-tuples)
26
+ - [Inheritance](#inheritance)
27
+ - [Operator Overloading](#operator-overloading)
28
+ - [Access Control](#access-control)
29
+ - [Declaration Order](#declaration-order)
30
+ - [Functions](#functions)
31
+ - [Inputs and Outputs](#inputs-and-outputs)
32
+ - [Write Short Functions](#write-short-functions)
33
+ - [Function Overloading](#function-overloading)
34
+ - [Default Arguments](#default-arguments)
35
+ - [Trailing Return Type Syntax](#trailing-return-type-syntax)
36
+ - [Google-Specific Magic](#google-specific-magic)
37
+ - [Ownership and Smart Pointers](#ownership-and-smart-pointers)
38
+ - [cpplint](#cpplint)
39
+ - [Other C++ Features](#other-c-features)
40
+ - [Rvalue References](#rvalue-references)
41
+ - [Friends](#friends)
42
+ - [Exceptions](#exceptions)
43
+ - [noexcept](#noexcept)
44
+ - [Run-Time Type Information (RTTI)](#run-time-type-information-rtti)
45
+ - [Casting](#casting)
46
+ - [Streams](#streams)
47
+ - [Preincrement and Predecrement](#preincrement-and-predecrement)
48
+ - [Use of const](#use-of-const)
49
+ - [Use of constexpr, constinit, and consteval](#use-of-constexpr-constinit-and-consteval)
50
+ - [Integer Types](#integer-types)
51
+ - [Floating-Point Types](#floating-point-types)
52
+ - [Architecture Portability](#architecture-portability)
53
+ - [Preprocessor Macros](#preprocessor-macros)
54
+ - [0 and nullptr/NULL](#0-and-nullptrnull)
55
+ - [sizeof](#sizeof)
56
+ - [Type Deduction (including auto)](#type-deduction-including-auto)
57
+ - [Class Template Argument Deduction](#class-template-argument-deduction)
58
+ - [Designated Initializers](#designated-initializers)
59
+ - [Lambda Expressions](#lambda-expressions)
60
+ - [Template Metaprogramming](#template-metaprogramming)
61
+ - [Concepts and Constraints](#concepts-and-constraints)
62
+ - [C++20 modules](#c20-modules)
63
+ - [Coroutines](#coroutines)
64
+ - [Boost](#boost)
65
+ - [Disallowed standard library features](#disallowed-standard-library-features)
66
+ - [Nonstandard Extensions](#nonstandard-extensions)
67
+ - [Aliases](#aliases)
68
+ - [Switch Statements](#switch-statements)
69
+ - [Inclusive Language](#inclusive-language)
70
+ - [Naming](#naming)
71
+ - [Choosing Names](#choosing-names)
72
+ - [File Names](#file-names)
73
+ - [Type Names](#type-names)
74
+ - [Concept Names](#concept-names)
75
+ - [Variable Names](#variable-names)
76
+ - [Constant Names](#constant-names)
77
+ - [Function Names](#function-names)
78
+ - [Namespace Names](#namespace-names)
79
+ - [Enumerator Names](#enumerator-names)
80
+ - [Template Parameter Names](#template-parameter-names)
81
+ - [Macro Names](#macro-names)
82
+ - [Aliases](#aliases)
83
+ - [Exceptions to Naming Rules](#exceptions-to-naming-rules)
84
+ - [Comments](#comments)
85
+ - [Comment Style](#comment-style)
86
+ - [File Comments](#file-comments)
87
+ - [Struct and Class Comments](#struct-and-class-comments)
88
+ - [Function Comments](#function-comments)
89
+ - [Variable Comments](#variable-comments)
90
+ - [Implementation Comments](#implementation-comments)
91
+ - [Punctuation, Spelling, and Grammar](#punctuation-spelling-and-grammar)
92
+ - [TODO Comments](#todo-comments)
93
+ - [Formatting](#formatting)
94
+ - [Line Length](#line-length)
95
+ - [Non-ASCII Characters](#non-ascii-characters)
96
+ - [Spaces vs. Tabs](#spaces-vs-tabs)
97
+ - [Function Declarations and Definitions](#function-declarations-and-definitions)
98
+ - [Lambda Expressions](#lambda-expressions)
99
+ - [Floating-point Literals](#floating-point-literals)
100
+ - [Function Calls](#function-calls)
101
+ - [Braced Initializer List Format](#braced-initializer-list-format)
102
+ - [Looping and branching statements](#looping-and-branching-statements)
103
+ - [Pointer and Reference Expressions and Types](#pointer-and-reference-expressions-and-types)
104
+ - [Boolean Expressions](#boolean-expressions)
105
+ - [Return Values](#return-values)
106
+ - [Variable and Array Initialization](#variable-and-array-initialization)
107
+ - [Preprocessor Directives](#preprocessor-directives)
108
+ - [Class Format](#class-format)
109
+ - [Constructor Initializer Lists](#constructor-initializer-lists)
110
+ - [Namespace Formatting](#namespace-formatting)
111
+ - [Horizontal Whitespace](#horizontal-whitespace)
112
+ - [Vertical Whitespace](#vertical-whitespace)
113
+ - [Exceptions to the Rules](#exceptions-to-the-rules)
114
+ - [Existing Non-conformant Code](#existing-non-conformant-code)
115
+ - [Windows Code](#windows-code)
116
+
117
+ <!-- end of toc -->
118
+
119
+ **GOOGLE C++ STYLE GUIDE**
120
+
121
+ **BACKGROUND**
122
+
123
+ C++ is one of the main development languages used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.
124
+
125
+ The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the codebase manageable while still allowing coders to use C++ language features productively.
126
+
127
+ *Style*, also known as readability, is what we call
128
+ the conventions that govern our C++ code. The term Style is a
129
+ bit of a misnomer, since these conventions cover far more than
130
+ just source file formatting.
131
+
132
+ Most open-source projects developed by Google conform to the requirements in this guide.
133
+
134
+ Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.
135
+
136
+ **GOALS OF THE STYLE GUIDE**
137
+
138
+ Why do we have this document?
139
+
140
+ There are a few core goals that we believe this guide should serve. These are the fundamental **why**s that underlie all of the individual rules. By bringing these ideas to the fore, we hope to ground discussions and make it clearer to our broader community why the rules are in place and why particular decisions have been made. If you understand what goals each rule is serving, it should be clearer to everyone when a rule may be waived (some can be), and what sort of argument or alternative would be necessary to change a rule in the guide.
141
+
142
+ The goals of the style guide as we currently see them are as follows:
143
+
144
+ Style rules should pull their weight : The benefit of a style rule must be large enough to justify asking all of our engineers to remember it. The benefit is measured relative to the codebase we would get without the rule, so a rule against a very harmful practice may still have a small benefit if people are unlikely to do it anyway. This principle mostly explains the rules we don't have, rather than the rules we do: for example, `goto` contravenes many of the following principles, but is already vanishingly rare, so the Style Guide doesn't discuss it.
145
+
146
+ Optimize for the reader, not the writer : Our codebase (and most individual components submitted to it) is expected to continue for quite some time. As a result, more time will be spent reading most of our code than writing it. We explicitly choose to optimize for the experience of our average software engineer reading, maintaining, and debugging code in our codebase rather than ease when writing said code. "Leave a trace for the reader" is a particularly common sub-point of this principle: When something surprising or unusual is happening in a snippet of code (for example, transfer of pointer ownership), leaving textual hints for the reader at the point of use is valuable (`std::unique_ptr` demonstrates the ownership transfer unambiguously at the call site).
147
+
148
+ Be consistent with existing code : Using one style consistently through our codebase lets us focus on other (more important) issues. Consistency also allows for automation: tools that format your code or adjust your `#include`s only work properly when your code is consistent with the expectations of the tooling. In many cases, rules that are attributed to "Be Consistent" boil down to "Just pick one and stop worrying about it"; the potential value of allowing flexibility on these points is outweighed by the cost of having people argue over them. However, there are limits to consistency; it is a good tie breaker when there is no clear technical argument, nor a long-term direction. It applies more heavily locally (per file, or for a tightly-related set of interfaces). Consistency should not generally be used as a justification to do things in an old style without considering the benefits of the new style, or the tendency of the codebase to converge on newer styles over time.
149
+
150
+ Be consistent with the broader C++ community when appropriate : Consistency with the way other organizations use C++ has value for the same reasons as consistency within our codebase. If a feature in the C++ standard solves a problem, or if some idiom is widely known and accepted, that's an argument for using it. However, sometimes standard features and idioms are flawed, or were just designed without our codebase's needs in mind. In those cases (as described below) it's appropriate to constrain or ban standard features. In some cases we prefer a homegrown or third-party library over a library defined in the C++ Standard, either out of perceived superiority or insufficient value to transition the codebase to the standard interface.
151
+
152
+ Avoid surprising or dangerous constructs : C++ has features that are more surprising or dangerous than one might think at a glance. Some style guide restrictions are in place to prevent falling into these pitfalls. There is a high bar for style guide waivers on such restrictions, because waiving such rules often directly risks compromising program correctness.
153
+
154
+ Avoid constructs that our average C++ programmer would find tricky or hard to maintain : C++ has features that may not be generally appropriate because of the complexity they introduce to the code. In widely used code, it may be more acceptable to use trickier language constructs, because any benefits of more complex implementation are multiplied widely by usage, and the cost in understanding the complexity does not need to be paid again when working with new portions of the codebase. When in doubt, waivers to rules of this type can be sought by asking your project leads. This is specifically important for our codebase because code ownership and team membership changes over time: even if everyone that works with some piece of code currently understands it, such understanding is not guaranteed to hold a few years from now.
155
+
156
+ Be mindful of our scale : With a codebase of 100+ million lines and thousands of engineers, some mistakes and simplifications for one engineer can become costly for many. For instance it's particularly important to avoid polluting the global namespace: name collisions across a codebase of hundreds of millions of lines are difficult to work with and hard to avoid if everyone puts things into the global namespace.
157
+
158
+ Concede to optimization when necessary : Performance optimizations can sometimes be necessary and appropriate, even when they conflict with the other principles of this document.
159
+
160
+ The intent of this document is to provide maximal guidance with reasonable restriction. As always, common sense and good taste should prevail. By this we specifically refer to the established conventions of the entire Google C++ community, not just your personal preferences or those of your team. Be skeptical about and reluctant to use clever or unusual constructs: the absence of a prohibition is not the same as a license to proceed. Use your judgment, and if you are unsure, please don't hesitate to ask your project leads to get additional input.
161
+
162
+ # C++ Version
163
+
164
+ Currently, code should target C++20, i.e., should not use C++23 features. The C++ version targeted by this guide will advance (aggressively) over time.
165
+
166
+ Do not use [non-standard extensions](#Nonstandard_Extensions).
167
+
168
+ Consider portability to other environments before using features from C++17 and C++20 in your project.
169
+
170
+ # Header Files
171
+
172
+ In general, every `.cc` file should have an associated `.h` file. There are some common exceptions, such as unit tests and small `.cc` files containing just a `main()` function.
173
+
174
+ Correct use of header files can make a huge difference to the readability, size and performance of your code.
175
+
176
+ The following rules will guide you through the various pitfalls of using header files.
177
+
178
+ ## Self-contained Headers
179
+
180
+ Header files should be self-contained (compile on their own) and end in `.h`. Non-header files that are meant for inclusion should end in `.inc` and be used sparingly.
181
+
182
+ All header files should be self-contained. Users and refactoring tools should not have to adhere to special conditions to include the header. Specifically, a header should have [header guards](#The__define_Guard) and include all other headers it needs.
183
+
184
+ When a header declares inline functions or templates that clients of the header will instantiate, the inline functions and templates must also have definitions in the header, either directly or in files it includes. Do not move these definitions to separately included header (`-inl.h`) files; this practice was common in the past, but is no longer allowed. When all instantiations of a template occur in one `.cc` file, either because they're [explicit](https://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation) or because the definition is accessible to only the `.cc` file, the template definition can be kept in that file.
185
+
186
+ There are rare cases where a file designed to be included is not self-contained. These are typically intended to be included at unusual locations, such as the middle of another file. They might not use [header guards](#The__define_Guard), and might not include their prerequisites. Name such files with the `.inc` extension. Use sparingly, and prefer self-contained headers when possible.
187
+
188
+ ## The #define Guard
189
+
190
+ All header files should have `#define` guards to prevent multiple inclusion. The format of the symbol name should be `<PROJECT>_<PATH>_<FILE>_H_`.
191
+
192
+ To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file `foo/src/bar/baz.h` in project `foo` should have the following guard:
193
+ ```
194
+ #ifndef FOO_BAR_BAZ_H_
195
+ #define FOO_BAR_BAZ_H_
196
+
197
+ ...
198
+
199
+ #endif // FOO_BAR_BAZ_H_
200
+ ```
201
+
202
+ ## Include What You Use
203
+
204
+ If a source or header file refers to a symbol defined elsewhere, the file should directly include a header file which properly intends to provide a declaration or definition of that symbol. It should not include header files for any other reason.
205
+
206
+ Do not rely on transitive inclusions. This allows people to remove no-longer-needed `#include` statements from their headers without breaking clients. This also applies to related headers
207
+
208
+ - `foo.cc` should include `bar.h` if it uses a symbol from it even if `foo.h` includes `bar.h`.
209
+
210
+ ## Forward Declarations
211
+
212
+ Avoid using forward declarations where possible. Instead, [include the headers you need](#Include_What_You_Use).
213
+
214
+ A "forward declaration" is a declaration of an entity without an associated definition.
215
+ ```
216
+ // In a C++ source file:
217
+ class B;
218
+ void FuncInB();
219
+ extern int variable_in_b;
220
+ ABSL_DECLARE_FLAG(flag_in_b);
221
+ ```
222
+
223
+ * Forward declarations can save compile time, as
224
+ `#include`s force the compiler to open
225
+ more files and process more input.
226
+ * Forward declarations can save on unnecessary
227
+ recompilation. `#include`s can force
228
+ your code to be recompiled more often, due to unrelated
229
+ changes in the header.
230
+
231
+ * Forward declarations can hide a dependency, allowing
232
+ user code to skip necessary recompilation when headers
233
+ change.
234
+ * A forward declaration as opposed to an `#include` statement
235
+ makes it difficult for automatic tooling to discover the module
236
+ defining the symbol.
237
+ * A forward declaration may be broken by subsequent
238
+ changes to the library. Forward declarations of functions
239
+ and templates can prevent the header owners from making
240
+ otherwise-compatible changes to their APIs, such as
241
+ widening a parameter type, adding a template parameter
242
+ with a default value, or migrating to a new namespace.
243
+ * Forward declaring symbols from namespace
244
+ `std::` yields undefined behavior.
245
+ * It can be difficult to determine whether a forward
246
+ declaration or a full `#include` is needed.
247
+ Replacing an `#include` with a forward
248
+ declaration can silently change the meaning of
249
+ code:
250
+ ```
251
+ // b.h:
252
+ struct B {};
253
+ struct D : B {};
254
+
255
+ // good_user.cc:
256
+ #include "b.h"
257
+ void f(B*);
258
+ void f(void*);
259
+ void test(D* x) { f(x); } // Calls f(B*)
260
+ ```
261
+
262
+ If the `#include` was replaced with forward decls for `B` and `D`, `test()` would call `f(void*)`.
263
+
264
+ - Forward declaring multiple symbols from a header can be more verbose than simply `#include`ing the header.
265
+ - Structuring code to enable forward declarations (e.g., using pointer members instead of object members) can make the code slower and more complex.
266
+
267
+ Try to avoid forward declarations of entities defined in another project.
268
+
269
+ ## Defining Functions in Header Files
270
+
271
+ Include the definition of a function at its point of declaration in a header file only when the definition is short. If the definition otherwise has a reason be in the header, put it in an internal part of the file. If necessary to make the definition ODR-safe, mark it with an `inline` specifier.
272
+
273
+ Functions defined in header files are sometimes referred to as "inline functions", which is a somewhat overloaded term that refers to several distinct but overlapping situations:
274
+
275
+ 1. A *textually inline* symbol's definition is exposed to the reader at
276
+ the point of declaration.
277
+ 2. A function or variable defined in a header file is *expandable inline*
278
+ since its definition is available for
279
+ [inline expansion](https://en.wikipedia.org/wiki/Inline_expansion)
280
+ by the compiler, which can lead to more efficient object code.
281
+ 3. *ODR-safe* entities do not violate the
282
+ ["One Definition Rule"](https://en.cppreference.com/w/cpp/language/definition),
283
+ which often requires the [inline](https://en.cppreference.com/w/cpp/language/inline)
284
+ keyword for things defined in header files
285
+ .
286
+
287
+ While functions tend to be a more common source of confusion, these definitions apply to variables as well, and so do the rules here.
288
+
289
+ * Defining a function textually in-line reduces boilerplate code for simple functions
290
+ like accessors and mutators.
291
+ * As noted above, function definitions in header files *can* lead to
292
+ more efficient object code for small functions due to inline expansion by the
293
+ compiler.
294
+ * Function templates and `constexpr` functions generally need to
295
+ be defined in the header file that declares them (but not necessarily the public part).
296
+
297
+ * Embedding a function definition in the public API makes the API harder to skim,
298
+ and incurs cognitive overhead for readers of that API- the more complex the function
299
+ the higher the cost.
300
+ * Public definitions expose implementation details that are at best harmless and
301
+ often extraneous.
302
+
303
+ Only define a function at its public declaration if it is short, say, 10 lines or fewer. Put longer function bodies in the `.cc` file unless they must be in the header for performance or technical reasons.
304
+
305
+ Even if a definition must be in the header, this is not a sufficient reason to put it within the public part. Instead, the definition can be in an internal part of the header, such as the [private](#Access_Control) section of a class, within a namespace that includes the word `internal`, or below a comment like `// Implementation details only below here`.
306
+
307
+ Once a definition is in a header file, it must be ODR-safe by having the `inline` specifier or being implicitly specified inline by being a function template or defined in a class body when first declared.
308
+ ```
309
+ template <typename T>
310
+ class Foo {
311
+ public:
312
+ int bar() { return bar_; }
313
+
314
+ void MethodWithHugeBody();
315
+
316
+ private:
317
+ int bar_;
318
+ };
319
+
320
+ // Implementation details only below here
321
+
322
+ template <typename T>
323
+ void Foo<T>::MethodWithHugeBody() {
324
+ ...
325
+ }
326
+ ```
327
+
328
+ ## Names and Order of Includes
329
+
330
+ Include headers in the following order: Related header, C system headers, C++ standard library headers, other libraries' headers, your project's headers.
331
+
332
+ All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory aliases `.` (the current directory) or `..` (the parent directory). For example, `google-awesome-project/src/base/logging.h` should be included as:
333
+ ```
334
+ #include "base/logging.h"
335
+ ```
336
+
337
+ Headers should only be included using an angle-bracketed path if the library requires you to do so. In particular, the following headers require angle brackets:
338
+
339
+ * C and C++ standard library headers (e.g., `<stdlib.h>`
340
+ and `<string>`).
341
+ * POSIX, Linux, and Windows system headers (e.g., `<unistd.h>`
342
+ and `<windows.h>`).
343
+ * In rare cases, third_party libraries (e.g., `<Python.h>`).
344
+
345
+ In `dir/foo.cc` or `dir/foo_test.cc`, whose main purpose is to implement or test the stuff in `dir2/foo2.h`, order your includes as follows:
346
+
347
+ 1. `dir2/foo2.h`.
348
+ 2. A blank line
349
+ 3. C system headers, and any other headers in angle brackets with the
350
+ `.h` extension, e.g., `<unistd.h>`,
351
+ `<stdlib.h>`, `<Python.h>`.
352
+ 4. A blank line
353
+ 5. C++ standard library headers (without file extension), e.g.,
354
+ `<algorithm>`, `<cstddef>`.
355
+ 6. A blank line
356
+ - Other libraries' `.h` files.
357
+ - A blank line
358
+ 7. Your project's `.h`
359
+ files.
360
+
361
+ Separate each non-empty group with one blank line.
362
+
363
+ With the preferred ordering, if the related header `dir2/foo2.h` omits any necessary includes, the build of `dir/foo.cc` or `dir/foo_test.cc` will break. Thus, this rule ensures that build breaks show up first for the people working on these files, not for innocent people in other packages.
364
+
365
+ `dir/foo.cc` and `dir2/foo2.h` are usually in the same directory (e.g., `base/basictypes_test.cc` and `base/basictypes.h`), but may sometimes be in different directories too.
366
+
367
+ Note that the C headers such as `stddef.h` are essentially interchangeable with their C++ counterparts (`cstddef`). Either style is acceptable, but prefer consistency with existing code.
368
+
369
+ Within each section the includes should be ordered alphabetically. Note that older code might not conform to this rule and should be fixed when convenient.
370
+
371
+ For example, the includes in `google-awesome-project/src/foo/internal/fooserver.cc` might look like this:
372
+ ```
373
+ #include "foo/server/fooserver.h"
374
+
375
+ #include <sys/types.h>
376
+ #include <unistd.h>
377
+
378
+ #include <string>
379
+ #include <vector>
380
+
381
+ #include "base/basictypes.h"
382
+ #include "foo/server/bar.h"
383
+ #include "third_party/absl/flags/flag.h"
384
+ ```
385
+
386
+ **Exception:**
387
+
388
+ Sometimes, system-specific code needs conditional includes. Such code can put conditional includes after other includes. Of course, keep your system-specific code small and localized. Example:
389
+ ```
390
+ #include "foo/public/fooserver.h"
391
+
392
+ #ifdef _WIN32
393
+ #include <windows.h>
394
+ #endif // _WIN32
395
+ ```
396
+
397
+ # Scoping
398
+
399
+ ## Namespaces
400
+
401
+ With few exceptions, place code in a namespace. Namespaces should have unique names based on the project name, and possibly its path. Do not use *using-directives* (e.g., `using namespace foo`). Do not use inline namespaces. For unnamed namespaces, see [Internal Linkage](#Internal_Linkage).
402
+
403
+ Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope.
404
+
405
+ Namespaces provide a method for preventing name conflicts in large programs while allowing most code to use reasonably short names.
406
+
407
+ For example, if two different projects have a class `Foo` in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, `project1::Foo` and `project2::Foo` are now distinct symbols that do not collide, and code within each project's namespace can continue to refer to `Foo` without the prefix.
408
+
409
+ Inline namespaces automatically place their names in the enclosing scope. Consider the following snippet, for example:
410
+ ```
411
+ namespace outer {
412
+ inline namespace inner {
413
+ void foo();
414
+ } // namespace inner
415
+ } // namespace outer
416
+ ```
417
+
418
+ The expressions `outer::inner::foo()` and `outer::foo()` are interchangeable. Inline namespaces are primarily intended for ABI compatibility across versions.
419
+
420
+ Namespaces can be confusing, because they complicate the mechanics of figuring out what definition a name refers to.
421
+
422
+ Inline namespaces, in particular, can be confusing because names aren't actually restricted to the namespace where they are declared. They are only useful as part of some larger versioning policy.
423
+
424
+ In some contexts, it's necessary to repeatedly refer to symbols by their fully-qualified names. For deeply-nested namespaces, this can add a lot of clutter.
425
+
426
+ Namespaces should be used as follows:
427
+
428
+ * Follow the rules on [Namespace Names](#Namespace_Names).
429
+ * Terminate multi-line namespaces with comments as shown in the given examples.
430
+ * Namespaces wrap the entire source file after
431
+ includes,
432
+ [gflags](https://gflags.github.io/gflags/) definitions/declarations
433
+ and forward declarations of classes from other namespaces.
434
+ ```
435
+ // In the .h file
436
+ namespace mynamespace {
437
+
438
+ // All declarations are within the namespace scope.
439
+ // Notice the lack of indentation.
440
+ class MyClass {
441
+ public:
442
+ ...
443
+ void Foo();
444
+ };
445
+
446
+ } // namespace mynamespace
447
+ ```
448
+
449
+ ```
450
+ // In the .cc file
451
+ namespace mynamespace {
452
+
453
+ // Definition of functions is within scope of the namespace.
454
+ void MyClass::Foo() {
455
+ ...
456
+ }
457
+
458
+ } // namespace mynamespace
459
+ ```
460
+
461
+ More complex `.cc` files might have additional details, like flags or using-declarations.
462
+ ```
463
+ #include "a.h"
464
+
465
+ ABSL_FLAG(bool, someflag, false, "a flag");
466
+
467
+ namespace mynamespace {
468
+
469
+ using ::foo::Bar;
470
+
471
+ ...code for mynamespace... // Code goes against the left margin.
472
+
473
+ } // namespace mynamespace
474
+ ```
475
+
476
+ - To place generated protocol message code in a namespace, use the `package` specifier in the `.proto` file. See [Protocol Buffer Packages](https://protobuf.dev/reference/cpp/cpp-generated/#package) for details.
477
+ - Do not declare anything in namespace `std`, including forward declarations of standard library classes. Declaring entities in namespace `std` is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.
478
+ - You may not use a *using-directive* to make all names from a namespace available.
479
+ ```
480
+ // Forbidden -- This pollutes the namespace.
481
+ using namespace foo;
482
+ ```
483
+ - Do not use *Namespace aliases* at namespace scope in header files except in explicitly marked internal-only namespaces, because anything imported into a namespace in a header file becomes part of the public API exported by that file. Namespace aliases can be used when those conditions don't apply, but they must have [appropriate names](#Naming_Aliases).
484
+ ```
485
+ // In a .h file, an alias must not be a separate API, or must be hidden in an
486
+ // implementation detail.
487
+ namespace librarian {
488
+
489
+ namespace internal { // Internal, not part of the API.
490
+ namespace sidetable = ::pipeline_diagnostics::sidetable;
491
+ } // namespace internal
492
+
493
+ inline void my_inline_function() {
494
+ // Local to a function.
495
+ namespace baz = ::foo::bar::baz;
496
+ ...
497
+ }
498
+
499
+ } // namespace librarian
500
+ ```
501
+
502
+ ```
503
+ // Remove uninteresting parts of some commonly used names in .cc files.
504
+ namespace sidetable = ::pipeline_diagnostics::sidetable;
505
+ ```
506
+ * Do not use inline namespaces.
507
+ * Use namespaces with "internal" in the name to document parts of an API that
508
+ should not be mentioned by users of the API.
509
+ ```
510
+ // We shouldn't use this internal name in non-absl code.
511
+ using ::absl::container_internal::ImplementationDetail;
512
+ ```
513
+
514
+ Note that there is still a risk of collision between libraries within a nested `internal` namespace, so give each library within a namespace a unique internal namespace by adding the library's filename. For example, `gshoe/widget.h` would use `gshoe::internal_widget` as opposed to just `gshoe::internal`.
515
+
516
+ - Single-line nested namespace declarations are preferred in new code, but are not required.
517
+ ```
518
+ namespace my_project::my_component {
519
+
520
+ ...
521
+
522
+ } // namespace my_project::my_component
523
+ ```
524
+
525
+ ## Internal Linkage
526
+
527
+ When definitions in a `.cc` file do not need to be referenced outside that file, give them internal linkage by placing them in an unnamed namespace or declaring them `static`. Do not use either of these constructs in `.h` files.
528
+
529
+ All declarations can be given internal linkage by placing them in unnamed namespaces. Functions and variables can also be given internal linkage by declaring them `static`. This means that anything you're declaring can't be accessed from another file. If a different file declares something with the same name, then the two entities are completely independent.
530
+
531
+ Use of internal linkage in `.cc` files is encouraged for all code that does not need to be referenced elsewhere. Do not use internal linkage in `.h` files.
532
+
533
+ Format unnamed namespaces like named namespaces. In the terminating comment, leave the namespace name empty:
534
+ ```
535
+ namespace {
536
+ ...
537
+ } // namespace
538
+ ```
539
+
540
+ ## Nonmember, Static Member, and Global Functions
541
+
542
+ Prefer placing nonmember functions in a namespace; use completely global functions rarely. Do not use a class simply to group static members. Static methods of a class should generally be closely related to instances of the class or the class's static data.
543
+
544
+ Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace.
545
+
546
+ Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies.
547
+
548
+ Sometimes it is useful to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Do not create classes only to group static members; this is no different than just giving the names a common prefix, and such grouping is usually unnecessary anyway.
549
+
550
+ If you define a nonmember function and it is only needed in its `.cc` file, use [internal linkage](#Internal_Linkage) to limit its scope.
551
+
552
+ ## Local Variables
553
+
554
+ Place a function's variables in the narrowest scope possible, and initialize variables in the declaration.
555
+
556
+ C++ allows you to declare variables anywhere in a function. We encourage you to declare them in a scope as local as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.,:
557
+ ```
558
+ int i;
559
+ i = f(); // Bad -- initialization separate from declaration.
560
+ ```
561
+
562
+ ```
563
+ int i = f(); // Good -- declaration has initialization.
564
+ ```
565
+
566
+ ```
567
+ int jobs = NumJobs();
568
+ // More code...
569
+ f(jobs); // Bad -- declaration separate from use.
570
+ ```
571
+
572
+ ```
573
+ int jobs = NumJobs();
574
+ f(jobs); // Good -- declaration immediately (or closely) followed by use.
575
+ ```
576
+
577
+ ```
578
+ std::vector<int> v;
579
+ v.push_back(1); // Prefer initializing using brace initialization.
580
+ v.push_back(2);
581
+ ```
582
+
583
+ ```
584
+ std::vector<int> v = {1, 2}; // Good -- v starts initialized.
585
+ ```
586
+
587
+ Variables needed for `if`, `while` and `for` statements should normally be declared within those statements, so that such variables are confined to those scopes. For example:
588
+ ```
589
+ while (const char* p = strchr(str, '/')) str = p + 1;
590
+ ```
591
+
592
+ There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.
593
+ ```
594
+ // Inefficient implementation:
595
+ for (int i = 0; i < 1000000; ++i) {
596
+ Foo f; // My ctor and dtor get called 1000000 times each.
597
+ f.DoSomething(i);
598
+ }
599
+ ```
600
+
601
+ It may be more efficient to declare such a variable used in a loop outside that loop:
602
+ ```
603
+ Foo f; // My ctor and dtor get called once each.
604
+ for (int i = 0; i < 1000000; ++i) {
605
+ f.DoSomething(i);
606
+ }
607
+ ```
608
+
609
+ ## Static and Global Variables
610
+
611
+ Objects with [static storage duration](http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration) are forbidden unless they are [trivially destructible](http://en.cppreference.com/w/cpp/types/is_destructible). Informally this means that the destructor does not do anything, even taking member and base destructors into account. More formally it means that the type has no user-defined or virtual destructor and that all bases and non-static members are trivially destructible. Static function-local variables may use dynamic initialization. Use of dynamic initialization for static class member variables or variables at namespace scope is discouraged, but allowed in limited circumstances; see below for details.
612
+
613
+ As a rule of thumb: a global variable satisfies these requirements if its declaration, considered in isolation, could be `constexpr`.
614
+
615
+ Every object has a storage duration, which correlates with its lifetime. Objects with static storage duration live from the point of their initialization until the end of the program. Such objects appear as variables at namespace scope ("global variables"), as static data members of classes, or as function-local variables that are declared with the `static` specifier. Function-local static variables are initialized when control first passes through their declaration; all other objects with static storage duration are initialized as part of program start-up. All objects with static storage duration are destroyed at program exit (which happens before unjoined threads are terminated).
616
+
617
+ Initialization may be dynamic, which means that something non-trivial happens during initialization. (For example, consider a constructor that allocates memory, or a variable that is initialized with the current process ID.) The other kind of initialization is static initialization. The two aren't quite opposites, though: static initialization *always* happens to objects with static storage duration (initializing the object either to a given constant or to a representation consisting of all bytes set to zero), whereas dynamic initialization happens after that, if required.
618
+
619
+ Global and static variables are very useful for a large number of applications: named constants, auxiliary data structures internal to some translation unit, command-line flags, logging, registration mechanisms, background infrastructure, etc.
620
+
621
+ Global and static variables that use dynamic initialization or have non-trivial destructors create complexity that can easily lead to hard-to-find bugs. Dynamic initialization is not ordered across translation units, and neither is destruction (except that destruction happens in reverse order of initialization). When one initialization refers to another variable with static storage duration, it is possible that this causes an object to be accessed before its lifetime has begun (or after its lifetime has ended). Moreover, when a program starts threads that are not joined at exit, those threads may attempt to access objects after their lifetime has ended if their destructor has already run.
622
+
623
+ **DECISION ON DESTRUCTION**
624
+
625
+ When destructors are trivial, their execution is not subject to ordering at all (they are effectively not "run"); otherwise we are exposed to the risk of accessing objects after the end of their lifetime. Therefore, we only allow objects with static storage duration if they are trivially destructible. Fundamental types (like pointers and `int`) are trivially destructible, as are arrays of trivially destructible types. Note that variables marked with `constexpr` are trivially destructible.
626
+ ```
627
+ const int kNum = 10; // Allowed
628
+
629
+ struct X { int n; };
630
+ const X kX[] = {{1}, {2}, {3}}; // Allowed
631
+
632
+ void foo() {
633
+ static const char* const kMessages[] = {"hello", "world"}; // Allowed
634
+ }
635
+
636
+ // Allowed: constexpr guarantees trivial destructor.
637
+ constexpr std::array<int, 3> kArray = {1, 2, 3};
638
+ ```
639
+
640
+ ```
641
+ // bad: non-trivial destructor
642
+ const std::string kFoo = "foo";
643
+
644
+ // Bad for the same reason, even though kBar is a reference (the
645
+ // rule also applies to lifetime-extended temporary objects).
646
+ const std::string& kBar = StrCat("a", "b", "c");
647
+
648
+ void bar() {
649
+ // Bad: non-trivial destructor.
650
+ static std::map<int, int> kData = {{1, 0}, {2, 0}, {3, 0}};
651
+ }
652
+ ```
653
+
654
+ Note that references are not objects, and thus they are not subject to the constraints on destructibility. The constraint on dynamic initialization still applies, though. In particular, a function-local static reference of the form `static T& t = *new T;` is allowed.
655
+
656
+ **DECISION ON INITIALIZATION**
657
+
658
+ Initialization is a more complex topic. This is because we must not only consider whether class constructors execute, but we must also consider the evaluation of the initializer:
659
+ ```
660
+ int n = 5; // Fine
661
+ int m = f(); // ? (Depends on f)
662
+ Foo x; // ? (Depends on Foo::Foo)
663
+ Bar y = g(); // ? (Depends on g and on Bar::Bar)
664
+ ```
665
+
666
+ All but the first statement expose us to indeterminate initialization ordering.
667
+
668
+ The concept we are looking for is called *constant initialization* in the formal language of the C++ standard. It means that the initializing expression is a constant expression, and if the object is initialized by a constructor call, then the constructor must be specified as `constexpr`, too:
669
+ ```
670
+ struct Foo { constexpr Foo(int) {} };
671
+
672
+ int n = 5; // Fine, 5 is a constant expression.
673
+ Foo x(2); // Fine, 2 is a constant expression and the chosen constructor is constexpr.
674
+ Foo a[] = { Foo(1), Foo(2), Foo(3) }; // Fine
675
+ ```
676
+
677
+ Constant initialization is always allowed. Constant initialization of static storage duration variables should be marked with `constexpr` or `constinit`. Any non-local static storage duration variable that is not so marked should be presumed to have dynamic initialization, and reviewed very carefully.
678
+
679
+ By contrast, the following initializations are problematic:
680
+ ```
681
+ // Some declarations used below.
682
+ time_t time(time_t*); // Not constexpr!
683
+ int f(); // Not constexpr!
684
+ struct Bar { Bar() {} };
685
+
686
+ // Problematic initializations.
687
+ time_t m = time(nullptr); // Initializing expression not a constant expression.
688
+ Foo y(f()); // Ditto
689
+ Bar b; // Chosen constructor Bar::Bar() not constexpr.
690
+ ```
691
+
692
+ Dynamic initialization of nonlocal variables is discouraged, and in general it is forbidden. However, we do permit it if no aspect of the program depends on the sequencing of this initialization with respect to all other initializations. Under those restrictions, the ordering of the initialization does not make an observable difference. For example:
693
+ ```
694
+ int p = getpid(); // Allowed, as long as no other static variable
695
+ // uses p in its own initialization.
696
+ ```
697
+
698
+ Dynamic initialization of static local variables is allowed (and common).
699
+
700
+ **COMMON PATTERNS**
701
+
702
+ * Global strings: if you require a named global or static string constant,
703
+ consider using a `constexpr` variable of
704
+ `string_view`, character array, or character pointer, pointing
705
+ to a string literal. String literals have static storage duration already
706
+ and are usually sufficient.
707
+ See [TotW #140](https://abseil.io/tips/140).
708
+ * Maps, sets, and other dynamic containers: if you require a static, fixed
709
+ collection, such as a set to search against or a lookup table, you cannot
710
+ use the dynamic containers from the standard library as a static variable,
711
+ since they have non-trivial destructors. Instead, consider
712
+ a simple array of trivial types, e.g., an array of arrays of ints (for a "map from int to
713
+ int"), or an array of pairs (e.g., pairs of `int` and `const
714
+ char*`). For small collections, linear search is entirely sufficient
715
+ (and efficient, due to memory locality); consider using the facilities from
716
+ [absl/algorithm/container.h](https://github.com/abseil/abseil-cpp/blob/master/absl/algorithm/container.h)
717
+ for the standard operations. If necessary, keep the collection in sorted
718
+ order and use a binary search algorithm.
719
+ If you do really prefer a dynamic container from the standard library, consider using
720
+ a function-local static pointer, as described below
721
+ .
722
+ * Smart pointers (`std::unique_ptr`, `std::shared_ptr`): smart
723
+ pointers execute cleanup during destruction and are therefore forbidden.
724
+ Consider whether your use case fits into one of the other patterns described
725
+ in this section. One simple solution is to use a plain pointer to a
726
+ dynamically allocated object and never delete it (see last item).
727
+ * Static variables of custom types: if you require static, constant data of
728
+ a type that you need to define yourself, give the type a trivial destructor
729
+ and a `constexpr` constructor.
730
+ * If all else fails, you can create an object dynamically and never delete
731
+ it by using a function-local static pointer or reference (e.g.,
732
+ `static const auto& impl = *new T(args...);`).
733
+
734
+ ## thread_local Variables
735
+
736
+ `thread_local` variables that aren't declared inside a function must be initialized with a true compile-time constant, and this must be enforced by using the [`constinit`](https://en.cppreference.com/w/cpp/language/constinit) attribute. Prefer `thread_local` over other ways of defining thread-local data.
737
+
738
+ Variables can be declared with the `thread_local` specifier:
739
+ ```
740
+ thread_local Foo foo = ...;
741
+ ```
742
+
743
+ Such a variable is actually a collection of objects, so that when different threads access it, they are actually accessing different objects. `thread_local` variables are much like [static storage duration variables](#Static_and_Global_Variables) in many respects. For instance, they can be declared at namespace scope, inside functions, or as static class members, but not as ordinary class members.
744
+
745
+ `thread_local` variable instances are initialized much like static variables, except that they must be initialized separately for each thread, rather than once at program startup. This means that `thread_local` variables declared within a function are safe, but other `thread_local` variables are subject to the same initialization-order issues as static variables (and more besides).
746
+
747
+ `thread_local` variables have a subtle destruction-order issue: during thread shutdown, `thread_local` variables will be destroyed in the opposite order of their initialization (as is generally true in C++). If code triggered by the destructor of any `thread_local` variable refers to any already-destroyed `thread_local` on that thread, we will get a particularly hard to diagnose use-after-free.
748
+
749
+ * Thread-local data is inherently safe from races (because only one thread
750
+ can ordinarily access it), which makes `thread_local` useful for
751
+ concurrent programming.
752
+ * `thread_local` is the only standard-supported way of creating
753
+ thread-local data.
754
+
755
+ * Accessing a `thread_local` variable may trigger execution of
756
+ an unpredictable and uncontrollable amount of other code during thread-start or
757
+ first use on a given thread.
758
+ * `thread_local` variables are effectively global variables,
759
+ and have all the drawbacks of global variables other than lack of
760
+ thread-safety.
761
+ * The memory consumed by a `thread_local` variable scales with
762
+ the number of running threads (in the worst case), which can be quite large
763
+ in a program.
764
+ * Data members cannot be `thread_local` unless they are also
765
+ `static`.
766
+ * We may suffer from use-after-free bugs if `thread_local` variables
767
+ have complex destructors. In particular, the destructor of any such variable must not
768
+ call any code (transitively) that refers to any potentially-destroyed
769
+ `thread_local`. This property is hard to enforce.
770
+ * Approaches for avoiding use-after-free in global/static contexts do not work for
771
+ `thread_local`s. Specifically, skipping destructors for globals and static
772
+ variables is allowable because their lifetimes end at program shutdown. Thus, any "leak"
773
+ is managed immediately by the OS cleaning up our memory and other resources. By
774
+ contrast, skipping destructors for `thread_local` variables leads to resource
775
+ leaks proportional to the total number of threads that terminate during the lifetime of
776
+ the program.
777
+
778
+ `thread_local` variables at class or namespace scope must be initialized with a true compile-time constant (i.e., they must have no dynamic initialization). To enforce this, `thread_local` variables at class or namespace scope must be annotated with [`constinit`](https://en.cppreference.com/w/cpp/language/constinit) (or `constexpr`, but that should be rare):
779
+ ```
780
+ constinit thread_local Foo foo = ...;
781
+ ```
782
+
783
+ `thread_local` variables inside a function have no initialization concerns, but still risk use-after-free during thread exit. Note that you can use a function-scope `thread_local` to simulate a class- or namespace-scope `thread_local` by defining a function or static method that exposes it:
784
+ ```
785
+ Foo& MyThreadLocalFoo() {
786
+ thread_local Foo result = ComplicatedInitialization();
787
+ return result;
788
+ }
789
+ ```
790
+
791
+ Note that `thread_local` variables will be destroyed whenever a thread exits. If the destructor of any such variable refers to any other (potentially-destroyed) `thread_local` we will suffer from hard to diagnose use-after-free bugs. Prefer trivial types, or types that provably run no user-provided code at destruction to minimize the potential of accessing any other `thread_local`.
792
+
793
+ `thread_local` should be preferred over other mechanisms for defining thread-local data.
794
+
795
+ # Classes
796
+
797
+ Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.
798
+
799
+ ## Doing Work in Constructors
800
+
801
+ Avoid virtual method calls in constructors, and avoid initialization that can fail if you can't signal an error.
802
+
803
+ It is possible to perform arbitrary initialization in the body of the constructor.
804
+
805
+ * No need to worry about whether the class has been initialized or
806
+ not.
807
+ * Objects that are fully initialized by constructor call can
808
+ be `const` and may also be easier to use with standard containers
809
+ or algorithms.
810
+
811
+ * If the work calls virtual functions, these calls
812
+ will not get dispatched to the subclass
813
+ implementations. Future modification to your class can
814
+ quietly introduce this problem even if your class is
815
+ not currently subclassed, causing much confusion.
816
+ * There is no easy way for constructors to signal errors, short of
817
+ crashing the program (not always appropriate) or using exceptions
818
+ (which are [forbidden](#Exceptions)).
819
+ * If the work fails, we now have an object whose initialization
820
+ code failed, so it may be an unusual state requiring a `bool
821
+ IsValid()` state checking mechanism (or similar) which is easy
822
+ to forget to call.
823
+ * You cannot take the address of a constructor, so whatever work
824
+ is done in the constructor cannot easily be handed off to, for
825
+ example, another thread.
826
+
827
+ Constructors should never call virtual functions. If appropriate for your code , terminating the program may be an appropriate error handling response. Otherwise, consider a factory function or `Init()` method as described in [TotW #42](https://abseil.io/tips/42) . Avoid `Init()` methods on objects with no other states that affect which public methods may be called (semi-constructed objects of this form are particularly hard to work with correctly).
828
+
829
+ ## Implicit Conversions
830
+
831
+ Do not define implicit conversions. Use the `explicit` keyword for conversion operators and single-argument constructors.
832
+
833
+ Implicit conversions allow an object of one type (called the source type) to be used where a different type (called the destination type) is expected, such as when passing an `int` argument to a function that takes a `double` parameter.
834
+
835
+ In addition to the implicit conversions defined by the language, users can define their own, by adding appropriate members to the class definition of the source or destination type. An implicit conversion in the source type is defined by a type conversion operator named after the destination type (e.g., `operator bool()`). An implicit conversion in the destination type is defined by a constructor that can take the source type as its only argument (or only argument with no default value).
836
+
837
+ The `explicit` keyword can be applied to a constructor or a conversion operator, to ensure that it can only be used when the destination type is explicit at the point of use, e.g., with a cast. This applies not only to implicit conversions, but to list initialization syntax:
838
+ ```
839
+ class Foo {
840
+ explicit Foo(int x, double y);
841
+ ...
842
+ };
843
+
844
+ void Func(Foo f);
845
+ ```
846
+
847
+ ```
848
+ Func({42, 3.14}); // Error
849
+ ```
850
+
851
+ This kind of code isn't technically an implicit conversion, but the language treats it as one as far as `explicit` is concerned.
852
+
853
+ * Implicit conversions can make a type more usable and
854
+ expressive by eliminating the need to explicitly name a type
855
+ when it's obvious.
856
+ * Implicit conversions can be a simpler alternative to
857
+ overloading, such as when a single
858
+ function with a `string_view` parameter takes the
859
+ place of separate overloads for `std::string` and
860
+ `const char*`.
861
+ * List initialization syntax is a concise and expressive
862
+ way of initializing objects.
863
+
864
+ * Implicit conversions can hide type-mismatch bugs, where the
865
+ destination type does not match the user's expectation, or
866
+ the user is unaware that any conversion will take place.
867
+ * Implicit conversions can make code harder to read, particularly
868
+ in the presence of overloading, by making it less obvious what
869
+ code is actually getting called.
870
+ * Constructors that take a single argument may accidentally
871
+ be usable as implicit type conversions, even if they are not
872
+ intended to do so.
873
+ * When a single-argument constructor is not marked
874
+ `explicit`, there's no reliable way to tell whether
875
+ it's intended to define an implicit conversion, or the author
876
+ simply forgot to mark it.
877
+ * Implicit conversions can lead to call-site ambiguities, especially
878
+ when there are bidirectional implicit conversions. This can be caused
879
+ either by having two types that both provide an implicit conversion,
880
+ or by a single type that has both an implicit constructor and an
881
+ implicit type conversion operator.
882
+ * List initialization can suffer from the same problems if
883
+ the destination type is implicit, particularly if the
884
+ list has only a single element.
885
+
886
+ Type conversion operators, and constructors that are callable with a single argument, must be marked `explicit` in the class definition. As an exception, copy and move constructors should not be `explicit`, since they do not perform type conversion.
887
+
888
+ Implicit conversions can sometimes be necessary and appropriate for types that are designed to be interchangeable, for example when objects of two types are just different representations of the same underlying value. In that case, contact your project leads to request a waiver of this rule.
889
+
890
+ Constructors that cannot be called with a single argument may omit `explicit`. Constructors that take a single `std::initializer_list` parameter should also omit `explicit`, in order to support copy-initialization (e.g., `MyType m = {1, 2};`).
891
+
892
+ ## Copyable and Movable Types
893
+
894
+ A class's public API must make clear whether the class is copyable, move-only, or neither copyable nor movable. Support copying and/or moving if these operations are clear and meaningful for your type.
895
+
896
+ A movable type is one that can be initialized and assigned from temporaries.
897
+
898
+ A copyable type is one that can be initialized or assigned from any other object of the same type (so is also movable by definition), with the stipulation that the value of the source does not change. `std::unique_ptr<int>` is an example of a movable but not copyable type (since the value of the source `std::unique_ptr<int>` must be modified during assignment to the destination). `int` and `std::string` are examples of movable types that are also copyable. (For `int`, the move and copy operations are the same; for `std::string`, there exists a move operation that is less expensive than a copy.)
899
+
900
+ For user-defined types, the copy behavior is defined by the copy constructor and the copy-assignment operator. Move behavior is defined by the move constructor and the move-assignment operator, if they exist, or by the copy constructor and the copy-assignment operator otherwise.
901
+
902
+ The copy/move constructors can be implicitly invoked by the compiler in some situations, e.g., when passing objects by value.
903
+
904
+ Objects of copyable and movable types can be passed and returned by value, which makes APIs simpler, safer, and more general. Unlike when passing objects by pointer or reference, there's no risk of confusion over ownership, lifetime, mutability, and similar issues, and no need to specify them in the contract. It also prevents non-local interactions between the client and the implementation, which makes them easier to understand, maintain, and optimize by the compiler. Further, such objects can be used with generic APIs that require pass-by-value, such as most containers, and they allow for additional flexibility in e.g., type composition.
905
+
906
+ Copy/move constructors and assignment operators are usually easier to define correctly than alternatives like `Clone()`, `CopyFrom()` or `Swap()`, because they can be generated by the compiler, either implicitly or with `= default`. They are concise, and ensure that all data members are copied. Copy and move constructors are also generally more efficient, because they don't require heap allocation or separate initialization and assignment steps, and they're eligible for optimizations such as [copy elision](http://en.cppreference.com/w/cpp/language/copy_elision).
907
+
908
+ Move operations allow the implicit and efficient transfer of resources out of rvalue objects. This allows a plainer coding style in some cases.
909
+
910
+ Some types do not need to be copyable, and providing copy operations for such types can be confusing, nonsensical, or outright incorrect. Types representing singleton objects (`Registerer`), objects tied to a specific scope (`Cleanup`), or closely coupled to object identity (`Mutex`) cannot be copied meaningfully. Copy operations for base class types that are to be used polymorphically are hazardous, because use of them can lead to [object slicing](https://en.wikipedia.org/wiki/Object_slicing). Defaulted or carelessly-implemented copy operations can be incorrect, and the resulting bugs can be confusing and difficult to diagnose.
911
+
912
+ Copy constructors are invoked implicitly, which makes the invocation easy to miss. This may cause confusion for programmers used to languages where pass-by-reference is conventional or mandatory. It may also encourage excessive copying, which can cause performance problems.
913
+
914
+ Every class's public interface must make clear which copy and move operations the class supports. This should usually take the form of explicitly declaring and/or deleting the appropriate operations in the `public` section of the declaration.
915
+
916
+ Specifically, a copyable class should explicitly declare the copy operations, a move-only class should explicitly declare the move operations, and a non-copyable/movable class should explicitly delete the copy operations. A copyable class may also declare move operations in order to support efficient moves. Explicitly declaring or deleting all four copy/move operations is permitted, but not required. If you provide a copy or move assignment operator, you must also provide the corresponding constructor.
917
+ ```
918
+ class Copyable {
919
+ public:
920
+ Copyable(const Copyable& other) = default;
921
+ Copyable& operator=(const Copyable& other) = default;
922
+
923
+ // The implicit move operations are suppressed by the declarations above.
924
+ // You may explicitly declare move operations to support efficient moves.
925
+ };
926
+
927
+ class MoveOnly {
928
+ public:
929
+ MoveOnly(MoveOnly&& other) = default;
930
+ MoveOnly& operator=(MoveOnly&& other) = default;
931
+
932
+ // The copy operations are implicitly deleted, but you can
933
+ // spell that out explicitly if you want:
934
+ MoveOnly(const MoveOnly&) = delete;
935
+ MoveOnly& operator=(const MoveOnly&) = delete;
936
+ };
937
+
938
+ class NotCopyableOrMovable {
939
+ public:
940
+ // Not copyable or movable
941
+ NotCopyableOrMovable(const NotCopyableOrMovable&) = delete;
942
+ NotCopyableOrMovable& operator=(const NotCopyableOrMovable&)
943
+ = delete;
944
+
945
+ // The move operations are implicitly disabled, but you can
946
+ // spell that out explicitly if you want:
947
+ NotCopyableOrMovable(NotCopyableOrMovable&&) = delete;
948
+ NotCopyableOrMovable& operator=(NotCopyableOrMovable&&)
949
+ = delete;
950
+ };
951
+ ```
952
+
953
+ These declarations/deletions can be omitted only if they are obvious:
954
+
955
+ * If the class has no `private` section, like a
956
+ [struct](#Structs_vs._Classes) or an interface-only base class,
957
+ then the copyability/movability can be determined by the
958
+ copyability/movability of any public data members.
959
+ * If a base class clearly isn't copyable or movable, derived classes
960
+ naturally won't be either. An interface-only base class that leaves these
961
+ operations implicit is not sufficient to make concrete subclasses clear.
962
+ * Note that if you explicitly declare or delete either the constructor or
963
+ assignment operation for copy, the other copy operation is not obvious and
964
+ must be declared or deleted. Likewise for move operations.
965
+
966
+ A type should not be copyable/movable if the meaning of copying/moving is unclear to a casual user, or if it incurs unexpected costs. Move operations for copyable types are strictly a performance optimization and are a potential source of bugs and complexity, so avoid defining them unless they are significantly more efficient than the corresponding copy operations. If your type provides copy operations, it is recommended that you design your class so that the default implementation of those operations is correct. Remember to review the correctness of any defaulted operations as you would any other code.
967
+
968
+ To eliminate the risk of slicing, prefer to make base classes abstract, by making their constructors protected, by declaring their destructors protected, or by giving them one or more pure virtual member functions. Prefer to avoid deriving from concrete classes.
969
+
970
+ ## Structs vs. Classes
971
+
972
+ Use a `struct` only for passive objects that carry data; everything else is a `class`.
973
+
974
+ The `struct` and `class` keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining.
975
+
976
+ `structs` should be used for passive objects that carry data, and may have associated constants. All fields must be public. The struct type itself must not have invariants that imply relationships between different fields, since direct user access to those fields may break those invariants, but users of a struct may have requirements and guarantees on particular uses of it. Constructors, destructors, and helper methods may be present; however, these methods must not require or enforce any invariants.
977
+
978
+ If more functionality or invariants are required, or struct has wide visibility and expected to evolve, then a `class` is more appropriate. If in doubt, make it a `class`.
979
+
980
+ For consistency with STL, you can use `struct` instead of `class` for stateless types, such as traits, [template metafunctions](#Template_metaprogramming), and some functors.
981
+
982
+ Note that member variables in structs and classes have [different naming rules](#Variable_Names).
983
+
984
+ ## Structs vs. Pairs and Tuples
985
+
986
+ Prefer to use a `struct` instead of a pair or a tuple whenever the elements can have meaningful names.
987
+
988
+ While using pairs and tuples can avoid the need to define a custom type, potentially saving work when *writing* code, a meaningful field name will almost always be much clearer when *reading* code than `.first`, `.second`, or `std::get<X>`. While C++14's introduction of `std::get<Type>` to access a tuple element by type rather than index (when the type is unique) can sometimes partially mitigate this, a field name is usually substantially clearer and more informative than a type.
989
+
990
+ Pairs and tuples may be appropriate in generic code where there are not specific meanings for the elements of the pair or tuple. Their use may also be required in order to interoperate with existing code or APIs.
991
+
992
+ ## Inheritance
993
+
994
+ Composition is often more appropriate than inheritance. When using inheritance, make it `public`.
995
+
996
+ When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the base class defines. "Interface inheritance" is inheritance from a pure abstract base class (one with no state or defined methods); all other inheritance is "implementation inheritance".
997
+
998
+ Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API.
999
+
1000
+ For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation.
1001
+
1002
+ Multiple inheritance is especially problematic, because it often imposes a higher performance overhead (in fact, the performance drop from single inheritance to multiple inheritance can often be greater than the performance drop from ordinary to virtual dispatch), and because it risks leading to "diamond" inheritance patterns, which are prone to ambiguity, confusion, and outright bugs.
1003
+
1004
+ All inheritance should be `public`. If you want to do private inheritance, you should be including an instance of the base class as a member instead. You may use `final` on classes when you don't intend to support using them as base classes.
1005
+
1006
+ Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: `Bar` subclasses `Foo` if it can reasonably be said that `Bar` "is a kind of" `Foo`.
1007
+
1008
+ Limit the use of `protected` to those member functions that might need to be accessed from subclasses. Note that [data members should be `private`](#Access_Control).
1009
+
1010
+ Explicitly annotate overrides of virtual functions or virtual destructors with exactly one of an `override` or (less frequently) `final` specifier. Do not use `virtual` when declaring an override. Rationale: A function or destructor marked `override` or `final` that is not an override of a base class virtual function will not compile, and this helps catch common errors. The specifiers serve as documentation; if no specifier is present, the reader has to check all ancestors of the class in question to determine if the function or destructor is virtual or not.
1011
+
1012
+ Multiple inheritance is permitted, but multiple *implementation* inheritance is strongly discouraged.
1013
+
1014
+ ## Operator Overloading
1015
+
1016
+ Overload operators judiciously. Do not use user-defined literals.
1017
+
1018
+ C++ permits user code to [declare overloaded versions of the built-in operators](http://en.cppreference.com/w/cpp/language/operators) using the `operator` keyword, so long as one of the parameters is a user-defined type. The `operator` keyword also permits user code to define new kinds of literals using `operator""`, and to define type-conversion functions such as `operator bool()`.
1019
+
1020
+ Operator overloading can make code more concise and intuitive by enabling user-defined types to behave the same as built-in types. Overloaded operators are the idiomatic names for certain operations (e.g., `==`, `<`, `=`, and `<<`), and adhering to those conventions can make user-defined types more readable and enable them to interoperate with libraries that expect those names.
1021
+
1022
+ User-defined literals are a very concise notation for creating objects of user-defined types.
1023
+
1024
+ * Providing a correct, consistent, and unsurprising
1025
+ set of operator overloads requires some care, and failure
1026
+ to do so can lead to confusion and bugs.
1027
+ * Overuse of operators can lead to obfuscated code,
1028
+ particularly if the overloaded operator's semantics
1029
+ don't follow convention.
1030
+ * The hazards of function overloading apply just as
1031
+ much to operator overloading, if not more so.
1032
+ * Operator overloads can fool our intuition into
1033
+ thinking that expensive operations are cheap, built-in
1034
+ operations.
1035
+ * Finding the call sites for overloaded operators may
1036
+ require a search tool that's aware of C++ syntax, rather
1037
+ than, e.g., grep.
1038
+ * If you get the argument type of an overloaded operator
1039
+ wrong, you may get a different overload rather than a
1040
+ compiler error. For example, `foo < bar`
1041
+ may do one thing, while `&foo < &bar`
1042
+ does something totally different.
1043
+ * Certain operator overloads are inherently hazardous.
1044
+ Overloading unary `&` can cause the same
1045
+ code to have different meanings depending on whether
1046
+ the overload declaration is visible. Overloads of
1047
+ `&&`, `||`, and `,`
1048
+ (comma) cannot match the evaluation-order semantics of the
1049
+ built-in operators.
1050
+ * Operators are often defined outside the class,
1051
+ so there's a risk of different files introducing
1052
+ different definitions of the same operator. If both
1053
+ definitions are linked into the same binary, this results
1054
+ in undefined behavior, which can manifest as subtle
1055
+ run-time bugs.
1056
+ * User-defined literals (UDLs) allow the creation of new
1057
+ syntactic forms that are unfamiliar even to experienced C++
1058
+ programmers, such as `"Hello World"sv` as a
1059
+ shorthand for `std::string_view("Hello World")`.
1060
+ Existing notations are clearer, though less terse.
1061
+ * Because they can't be namespace-qualified, uses of UDLs also require
1062
+ use of either using-directives (which [we ban](#Namespaces)) or
1063
+ using-declarations (which [we ban in header files](#Aliases) except
1064
+ when the imported names are part of the interface exposed by the header
1065
+ file in question). Given that header files would have to avoid UDL
1066
+ suffixes, we prefer to avoid having conventions for literals differ
1067
+ between header files and source files.
1068
+
1069
+ Define overloaded operators only if their meaning is obvious, unsurprising, and consistent with the corresponding built-in operators. For example, use `|` as a bitwise- or logical-or, not as a shell-style pipe.
1070
+
1071
+ Define operators only on your own types. More precisely, define them in the same headers, `.cc` files, and namespaces as the types they operate on. That way, the operators are available wherever the type is, minimizing the risk of multiple definitions. If possible, avoid defining operators as templates, because they must satisfy this rule for any possible template arguments. If you define an operator, also define any related operators that make sense, and make sure they are defined consistently.
1072
+
1073
+ Prefer to define non-modifying binary operators as non-member functions. If a binary operator is defined as a class member, implicit conversions will apply to the right-hand argument, but not the left-hand one. It will confuse your users if `a + b` compiles but `b + a` doesn't.
1074
+
1075
+ For a type `T` whose values can be compared for equality, define a non-member `operator==` and document when two values of type `T` are considered equal. If there is a single obvious notion of when a value `t1` of type `T` is less than another such value `t2` then you may also define `operator<=>`, which should be consistent with `operator==`. Prefer not to overload the other comparison and ordering operators.
1076
+
1077
+ Don't go out of your way to avoid defining operator overloads. For example, prefer to define `==`, `=`, and `<<`, rather than `Equals()`, `CopyFrom()`, and `PrintTo()`. Conversely, don't define operator overloads just because other libraries expect them. For example, if your type doesn't have a natural ordering, but you want to store it in a `std::set`, use a custom comparator rather than overloading `<`.
1078
+
1079
+ Do not overload `&&`, `||`, `,` (comma), or unary `&`. Do not overload `operator""`, i.e., do not introduce user-defined literals. Do not use any such literals provided by others (including the standard library).
1080
+
1081
+ Type conversion operators are covered in the section on [implicit conversions](#Implicit_Conversions). The `=` operator is covered in the section on [copy constructors](#Copy_Constructors). Overloading `<<` for use with streams is covered in the section on [streams](#Streams). See also the rules on [function overloading](#Function_Overloading), which apply to operator overloading as well.
1082
+
1083
+ ## Access Control
1084
+
1085
+ Make classes' data members `private`, unless they are [constants](#Constant_Names). This simplifies reasoning about invariants, at the cost of some easy boilerplate in the form of accessors (usually `const`) if necessary.
1086
+
1087
+ For technical reasons, we allow data members of a test fixture class defined in a `.cc` file to be `protected` when using [Google Test](https://github.com/google/googletest). If a test fixture class is defined outside of the `.cc` file it is used in, for example in a `.h` file, make data members `private`.
1088
+
1089
+ ## Declaration Order
1090
+
1091
+ Group similar declarations together, placing `public` parts earlier.
1092
+
1093
+ A class definition should usually start with a `public:` section, followed by `protected:`, then `private:`. Omit sections that would be empty.
1094
+
1095
+ Within each section, prefer grouping similar kinds of declarations together, and prefer the following order:
1096
+
1097
+ 1. Types and type aliases (`typedef`, `using`,
1098
+ `enum`, nested structs and classes, and `friend` types)
1099
+ 2. (Optionally, for structs only) non-`static` data members
1100
+ 3. Static constants
1101
+ 4. Factory functions
1102
+ 5. Constructors and assignment operators
1103
+ 6. Destructor
1104
+ 7. All other functions (`static` and non-`static` member
1105
+ functions, and `friend` functions)
1106
+ 8. All other data members (static and non-static)
1107
+
1108
+ Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See [Defining Functions in Header Files](#Defining_Functions_in_Header_Files) for more details.
1109
+
1110
+ # Functions
1111
+
1112
+ ## Inputs and Outputs
1113
+
1114
+ The output of a C++ function is naturally provided via a return value and sometimes via output parameters (or in/out parameters).
1115
+
1116
+ Prefer using return values over output parameters: they improve readability, and often provide the same or better performance. See [TotW #176](https://abseil.io/tips/176).
1117
+
1118
+ Prefer to return by value or, failing that, return by reference. Avoid returning a raw pointer unless it can be null.
1119
+
1120
+ Parameters are either inputs to the function, outputs from the function, or both. Non-optional input parameters should usually be values or `const` references, while non-optional output and input/output parameters should usually be references (which cannot be null). Generally, use `std::optional` to represent optional by-value inputs, and use a `const` pointer when the non-optional form would have used a reference. Use non-`const` pointers to represent optional outputs and optional input/output parameters.
1121
+
1122
+ Avoid defining functions that require a reference parameter to outlive the call. In some cases reference parameters can bind to temporaries, leading to lifetime bugs. Instead, find a way to eliminate the lifetime requirement (for example, by copying the parameter), or pass retained parameters by pointer and document the lifetime and non-null requirements. See [TotW 116](https://abseil.io/tips/116) for more.
1123
+
1124
+ When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Variadic functions may also require unusual parameter ordering.
1125
+
1126
+ ## Write Short Functions
1127
+
1128
+ Prefer small and focused functions.
1129
+
1130
+ We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program.
1131
+
1132
+ Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. Small functions are also easier to test.
1133
+
1134
+ You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces.
1135
+
1136
+ ## Function Overloading
1137
+
1138
+ Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called.
1139
+
1140
+ You may write a function that takes a `const std::string&` and overload it with another that takes `const char*`. However, in this case consider `std::string_view` instead.
1141
+ ```
1142
+ class MyClass {
1143
+ public:
1144
+ void Analyze(const std::string& text);
1145
+ void Analyze(const char* text, size_t textlen);
1146
+ };
1147
+ ```
1148
+
1149
+ Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors.
1150
+
1151
+ Overloading based on `const` or ref qualification may make utility code more usable, more efficient, or both. See [TotW #148](https://abseil.io/tips/148) for more.
1152
+
1153
+ If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function.
1154
+
1155
+ You may overload a function when there are no semantic differences between variants. These overloads may vary in types, qualifiers, or argument count. However, a reader of such a call must not need to know which member of the overload set is chosen, only that **something** from the set is being called.
1156
+
1157
+ To reflect this unified design, prefer a single, comprehensive "umbrella" comment that documents the entire overload set and is placed before the first declaration.
1158
+
1159
+ Where a reader might have difficulty connecting the umbrella comment to a specific overload, it's okay to have a comment for specific overloads.
1160
+
1161
+ ## Default Arguments
1162
+
1163
+ Default arguments are allowed on non-virtual functions when the default is guaranteed to always have the same value. Follow the same restrictions as for [function overloading](#Function_Overloading), and prefer overloaded functions if the readability gained with default arguments doesn't outweigh the downsides below.
1164
+
1165
+ Often you have a function that uses default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Compared to overloading the function, default arguments have a cleaner syntax, with less boilerplate and a clearer distinction between 'required' and 'optional' arguments.
1166
+
1167
+ Defaulted arguments are another way to achieve the semantics of overloaded functions, so all the [reasons not to overload functions](#Function_Overloading) apply.
1168
+
1169
+ The defaults for arguments in a virtual function call are determined by the static type of the target object, and there's no guarantee that all overrides of a given function declare the same defaults.
1170
+
1171
+ Default parameters are re-evaluated at each call site, which can bloat the generated code. Readers may also expect the default's value to be fixed at the declaration instead of varying at each call.
1172
+
1173
+ Function pointers are confusing in the presence of default arguments, since the function signature often doesn't match the call signature. Adding function overloads avoids these problems.
1174
+
1175
+ Default arguments are banned on virtual functions, where they don't work properly, and in cases where the specified default might not evaluate to the same value depending on when it was evaluated. (For example, don't write `void f(int n = counter++);`.)
1176
+
1177
+ In some other cases, default arguments can improve the readability of their function declarations enough to overcome the downsides above, so they are allowed. When in doubt, use overloads.
1178
+
1179
+ ## Trailing Return Type Syntax
1180
+
1181
+ Use trailing return types only where using the ordinary syntax (leading return types) is impractical or much less readable.
1182
+
1183
+ C++ allows two different forms of function declarations. In the older form, the return type appears before the function name. For example:
1184
+ ```
1185
+ int Foo(int x);
1186
+ ```
1187
+
1188
+ The newer form uses the `auto` keyword before the function name and a trailing return type after the argument list. For example, the declaration above could equivalently be written:
1189
+ ```
1190
+ auto Foo(int x) -> int;
1191
+ ```
1192
+
1193
+ The trailing return type is in the function's scope. This doesn't make a difference for a simple case like `int` but it matters for more complicated cases, like types declared in class scope or types written in terms of the function parameters.
1194
+
1195
+ Trailing return types are the only way to explicitly specify the return type of a [lambda expression](#Lambda_expressions). In some cases the compiler is able to deduce a lambda's return type, but not in all cases. Even when the compiler can deduce it automatically, sometimes specifying it explicitly would be clearer for readers.
1196
+
1197
+ Sometimes it's easier and more readable to specify a return type after the function's parameter list has already appeared. This is particularly true when the return type depends on template parameters. For example:
1198
+ ```
1199
+ template <typename T, typename U>
1200
+ auto Add(T t, U u) -> decltype(t + u);
1201
+ ```
1202
+
1203
+ versus
1204
+ ```
1205
+ template <typename T, typename U>
1206
+ decltype(declval<T&>() + declval<U&>()) Add(T t, U u);
1207
+ ```
1208
+
1209
+ Trailing return type syntax has no analogue in C++-like languages such as C and Java, so some readers may find it unfamiliar.
1210
+
1211
+ Existing codebases have an enormous number of function declarations that aren't going to get changed to use the new syntax, so the realistic choices are using the old syntax only or using a mixture of the two. Using a single version is better for uniformity of style.
1212
+
1213
+ In most cases, continue to use the older style of function declaration where the return type goes before the function name. Use the new trailing-return-type form only in cases where it's required (such as lambdas) or where, by putting the type after the function's parameter list, it allows you to write the type in a much more readable way. The latter case should be rare; it's mostly an issue in fairly complicated template code, which is [discouraged in most cases](#Template_metaprogramming).
1214
+
1215
+ # Google-Specific Magic
1216
+
1217
+ There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.
1218
+
1219
+ ## Ownership and Smart Pointers
1220
+
1221
+ Prefer to have single, fixed owners for dynamically allocated objects. Prefer to transfer ownership with smart pointers.
1222
+
1223
+ "Ownership" is a bookkeeping technique for managing dynamically allocated memory (and other resources). The owner of a dynamically allocated object is an object or function that is responsible for ensuring that it is deleted when no longer needed. Ownership can sometimes be shared, in which case the last owner is typically responsible for deleting it. Even when ownership is not shared, it can be transferred from one piece of code to another.
1224
+
1225
+ "Smart" pointers are classes that act like pointers, e.g., by overloading the `*` and `->` operators. Some smart pointer types can be used to automate ownership bookkeeping, to ensure these responsibilities are met. [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) is a smart pointer type which expresses exclusive ownership of a dynamically allocated object; the object is deleted when the `std::unique_ptr` goes out of scope. It cannot be copied, but can be *moved* to represent ownership transfer. [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) is a smart pointer type that expresses shared ownership of a dynamically allocated object. `std::shared_ptr`s can be copied; ownership of the object is shared among all copies, and the object is deleted when the last `std::shared_ptr` is destroyed.
1226
+
1227
+ * It's virtually impossible to manage dynamically
1228
+ allocated memory without some sort of ownership
1229
+ logic.
1230
+ * Transferring ownership of an object can be cheaper
1231
+ than copying it (if copying it is even possible).
1232
+ * Transferring ownership can be simpler than
1233
+ 'borrowing' a pointer or reference, because it reduces
1234
+ the need to coordinate the lifetime of the object
1235
+ between the two users.
1236
+ * Smart pointers can improve readability by making
1237
+ ownership logic explicit, self-documenting, and
1238
+ unambiguous.
1239
+ * Smart pointers can eliminate manual ownership
1240
+ bookkeeping, simplifying the code and ruling out large
1241
+ classes of errors.
1242
+ * For `const` objects, shared ownership can be a simple
1243
+ and efficient alternative to deep copying.
1244
+
1245
+ * Ownership must be represented and transferred via
1246
+ pointers (whether smart or plain). Pointer semantics
1247
+ are more complicated than value semantics, especially
1248
+ in APIs: you have to worry not just about ownership,
1249
+ but also aliasing, lifetime, and mutability, among
1250
+ other issues.
1251
+ * The performance costs of value semantics are often
1252
+ overestimated, so the performance benefits of ownership
1253
+ transfer might not justify the readability and
1254
+ complexity costs.
1255
+ * APIs that transfer ownership force their clients
1256
+ into a single memory management model.
1257
+ * Code using smart pointers is less explicit about
1258
+ where the resource releases take place.
1259
+ * `std::unique_ptr` expresses ownership
1260
+ transfer using move semantics, which can be complex and
1261
+ may confuse some programmers.
1262
+ * Shared ownership can be a tempting alternative to
1263
+ careful ownership design, obfuscating the design of a
1264
+ system.
1265
+ * Shared ownership requires explicit bookkeeping at
1266
+ run-time, which can be costly.
1267
+ * In some cases (e.g., cyclic references), objects
1268
+ with shared ownership may never be deleted.
1269
+ * Smart pointers are not perfect substitutes for
1270
+ plain pointers.
1271
+
1272
+ If dynamic allocation is necessary, prefer to keep ownership with the code that allocated it. If other code needs access to the object, consider passing it a copy, or passing a pointer or reference without transferring ownership. Prefer to use `std::unique_ptr` to make ownership transfer explicit. For example:
1273
+ ```
1274
+ std::unique_ptr<Foo> FooFactory();
1275
+ void FooConsumer(std::unique_ptr<Foo> ptr);
1276
+ ```
1277
+
1278
+ Do not design your code to use shared ownership without a very good reason. One such reason is to avoid expensive copy operations, but you should only do this if the performance benefits are significant, and the underlying object is immutable (i.e., `std::shared_ptr<const Foo>`). If you do use shared ownership, prefer to use `std::shared_ptr`.
1279
+
1280
+ Never use `std::auto_ptr`. Instead, use `std::unique_ptr`.
1281
+
1282
+ ## cpplint
1283
+
1284
+ Use `cpplint.py` to detect style errors.
1285
+
1286
+ `cpplint.py` is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool.
1287
+
1288
+ Some projects have instructions on how to run `cpplint.py` from their project tools. If the project you are contributing to does not, you can download [`cpplint.py`](https://raw.githubusercontent.com/cpplint/cpplint/HEAD/cpplint.py) separately.
1289
+
1290
+ # Other C++ Features
1291
+
1292
+ ## Rvalue References
1293
+
1294
+ Use rvalue references only in certain special cases listed below.
1295
+
1296
+ Rvalue references are a type of reference that can only bind to temporary objects. The syntax is similar to traditional reference syntax. For example, `void f(std::string&& s);` declares a function whose argument is an rvalue reference to a `std::string`.
1297
+
1298
+ When the token '&&' is applied to an unqualified template argument in a function parameter, special template argument deduction rules apply. Such a reference is called a forwarding reference.
1299
+
1300
+ * Defining a move constructor (a constructor taking
1301
+ an rvalue reference to the class type) makes it
1302
+ possible to move a value instead of copying it. If
1303
+ `v1` is a `std::vector<std::string>`,
1304
+ for example, then `auto v2(std::move(v1))`
1305
+ will probably just result in some simple pointer
1306
+ manipulation instead of copying a large amount of data.
1307
+ In many cases this can result in a major performance
1308
+ improvement.
1309
+ * Rvalue references make it possible to implement
1310
+ types that are movable but not copyable, which can be
1311
+ useful for types that have no sensible definition of
1312
+ copying but where you might still want to pass them as
1313
+ function arguments, put them in containers, etc.
1314
+ * `std::move` is necessary to make
1315
+ effective use of some standard-library types, such as
1316
+ `std::unique_ptr`.
1317
+ * [Forwarding references](#Forwarding_references) which
1318
+ use the rvalue reference token make it possible to write a
1319
+ generic function wrapper that forwards its arguments to
1320
+ another function, and works whether or not its
1321
+ arguments are temporary objects and/or const.
1322
+ This is called 'perfect forwarding'.
1323
+
1324
+ * Rvalue references are not yet widely understood. Rules like reference
1325
+ collapsing and the special deduction rule for forwarding references
1326
+ are somewhat obscure.
1327
+ * Rvalue references are often misused. Using rvalue
1328
+ references is counter-intuitive in signatures where the argument is expected
1329
+ to have a valid specified state after the function call, or where no move
1330
+ operation is performed.
1331
+
1332
+ Do not use rvalue references (or apply the `&&` qualifier to methods), except as follows:
1333
+
1334
+ * You may use them to define move constructors and move assignment
1335
+ operators (as described in
1336
+ [Copyable and Movable Types](#Copyable_Movable_Types)).
1337
+ * You may use them to define `&&`-qualified methods that
1338
+ logically "consume" `*this`, leaving it in an unusable
1339
+ or empty state. Note that this applies only to method qualifiers (which come
1340
+ after the closing parenthesis of the function signature); if you want to
1341
+ "consume" an ordinary function parameter, prefer to pass it by value.
1342
+ * You may use forwarding references in conjunction with `std::forward`,
1343
+ to support perfect forwarding.
1344
+ * You may use them to define pairs of overloads, such as one taking
1345
+ `Foo&&` and the other taking `const Foo&`.
1346
+ Usually the preferred solution is just to pass by value, but an overloaded
1347
+ pair of functions sometimes yields better performance, for example if the
1348
+ functions sometimes don't consume the input. As always: if you're writing
1349
+ more complicated code for the sake of performance, make sure you have evidence
1350
+ that it actually helps.
1351
+
1352
+ ## Friends
1353
+
1354
+ We allow use of `friend` classes and functions, within reason.
1355
+
1356
+ Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of `friend` is to have a `FooBuilder` class be a friend of `Foo` so that it can construct the inner state of `Foo` correctly, without exposing this state to the world. In some cases it may be useful to make a unit test class a friend of the class it tests.
1357
+
1358
+ Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member `public` when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members.
1359
+
1360
+ ## Exceptions
1361
+
1362
+ We do not use C++ exceptions.
1363
+
1364
+ * Exceptions allow higher levels of an application to
1365
+ decide how to handle "can't happen" failures in deeply
1366
+ nested functions, without the obscuring and error-prone
1367
+ bookkeeping of error codes.
1368
+
1369
+ * Exceptions are used by most other
1370
+ modern languages. Using them in C++ would make it more
1371
+ consistent with Python, Java, and the C++ that others
1372
+ are familiar with.
1373
+
1374
+ * Some third-party C++ libraries use exceptions, and
1375
+ turning them off internally makes it harder to
1376
+ integrate with those libraries.
1377
+ * Exceptions are the only way for a constructor to
1378
+ fail. We can simulate this with a factory function or
1379
+ an `Init()` method, but these require heap
1380
+ allocation or a new "invalid" state, respectively.
1381
+ * Exceptions are really handy in testing
1382
+ frameworks.
1383
+
1384
+ * When you add a `throw` statement to an
1385
+ existing function, you must examine all of its
1386
+ transitive callers. Either they must make at least the
1387
+ basic exception safety guarantee, or they must never
1388
+ catch the exception and be happy with the program
1389
+ terminating as a result. For instance, if
1390
+ `f()` calls `g()` calls
1391
+ `h()`, and `h` throws an
1392
+ exception that `f` catches, `g`
1393
+ has to be careful or it may not clean up properly.
1394
+ * More generally, exceptions make the control flow of
1395
+ programs difficult to evaluate by looking at code:
1396
+ functions may return in places you don't expect. This
1397
+ causes maintainability and debugging difficulties. You
1398
+ can minimize this cost via some rules on how and where
1399
+ exceptions can be used, but at the cost of more that a
1400
+ developer needs to know and understand.
1401
+ * Exception safety requires both RAII and different
1402
+ coding practices. Lots of supporting machinery is
1403
+ needed to make writing correct exception-safe code
1404
+ easy. Further, to avoid requiring readers to understand
1405
+ the entire call graph, exception-safe code must isolate
1406
+ logic that writes to persistent state into a "commit"
1407
+ phase. This will have both benefits and costs (perhaps
1408
+ where you're forced to obfuscate code to isolate the
1409
+ commit). Allowing exceptions would force us to always
1410
+ pay those costs even when they're not worth it.
1411
+ * Turning on exceptions adds data to each binary
1412
+ produced, increasing compile time (probably slightly)
1413
+ and possibly increasing address space pressure.
1414
+ * The availability of exceptions may encourage
1415
+ developers to throw them when they are not appropriate
1416
+ or recover from them when it's not safe to do so. For
1417
+ example, invalid user input should not cause exceptions
1418
+ to be thrown. We would need to make the style guide
1419
+ even longer to document these restrictions!
1420
+
1421
+ On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.
1422
+
1423
+ Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.
1424
+
1425
+ Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.
1426
+
1427
+ This prohibition also applies to exception handling related features such as `std::exception_ptr` and `std::nested_exception`.
1428
+
1429
+ There is an [exception](#Windows_Code) to this rule (no pun intended) for Windows code.
1430
+
1431
+ ## noexcept
1432
+
1433
+ Specify `noexcept` when it is useful and correct.
1434
+
1435
+ The `noexcept` specifier is used to specify whether a function will throw exceptions or not. If an exception escapes from a function marked `noexcept`, the program crashes via `std::terminate`.
1436
+
1437
+ The `noexcept` operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions.
1438
+
1439
+ * Specifying move constructors as `noexcept`
1440
+ improves performance in some cases, e.g.,
1441
+ `std::vector<T>::resize()` moves rather than
1442
+ copies the objects if T's move constructor is
1443
+ `noexcept`.
1444
+ * Specifying `noexcept` on a function can
1445
+ trigger compiler optimizations in environments where
1446
+ exceptions are enabled, e.g., compiler does not have to
1447
+ generate extra code for stack-unwinding, if it knows
1448
+ that no exceptions can be thrown due to a
1449
+ `noexcept` specifier.
1450
+
1451
+ * In projects following this guide
1452
+ that have exceptions disabled it is hard
1453
+ to ensure that `noexcept`
1454
+ specifiers are correct, and hard to define what
1455
+ correctness even means.
1456
+ * It's hard, if not impossible, to undo `noexcept`
1457
+ because it eliminates a guarantee that callers may be relying
1458
+ on, in ways that are hard to detect.
1459
+
1460
+ You may use `noexcept` when it is useful for performance if it accurately reflects the intended semantics of your function, i.e., that if an exception is somehow thrown from within the function body then it represents a fatal error. You can assume that `noexcept` on move constructors has a meaningful performance benefit. If you think there is significant performance benefit from specifying `noexcept` on some other function, please discuss it with your project leads.
1461
+
1462
+ Prefer unconditional `noexcept` if exceptions are completely disabled (i.e., most Google C++ environments). Otherwise, use conditional `noexcept` specifiers with simple conditions, in ways that evaluate false only in the few cases where the function could potentially throw. The tests might include type traits check on whether the involved operation might throw (e.g., `std::is_nothrow_move_constructible` for move-constructing objects), or on whether allocation can throw (e.g., `absl::default_allocator_is_nothrow` for standard default allocation). Note in many cases the only possible cause for an exception is allocation failure (we believe move constructors should not throw except due to allocation failure), and there are many applications where it's appropriate to treat memory exhaustion as a fatal error rather than an exceptional condition that your program should attempt to recover from. Even for other potential failures you should prioritize interface simplicity over supporting all possible exception throwing scenarios: instead of writing a complicated `noexcept` clause that depends on whether a hash function can throw, for example, simply document that your component doesn't support hash functions throwing and make it unconditionally `noexcept`.
1463
+
1464
+ ## Run-Time Type Information (RTTI)
1465
+
1466
+ Avoid using run-time type information (RTTI).
1467
+
1468
+ RTTI allows a programmer to query the C++ class of an object at run-time. This is done by use of `typeid` or `dynamic_cast`.
1469
+
1470
+ The standard alternatives to RTTI (described below) require modification or redesign of the class hierarchy in question. Sometimes such modifications are infeasible or undesirable, particularly in widely-used or mature code.
1471
+
1472
+ RTTI can be useful in some unit tests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. It is also useful in managing the relationship between objects and their mocks.
1473
+
1474
+ RTTI is useful when considering multiple abstract objects. Consider
1475
+ ```
1476
+ bool Base::Equal(Base* other) = 0;
1477
+ bool Derived::Equal(Base* other) {
1478
+ Derived* that = dynamic_cast<Derived*>(other);
1479
+ if (that == nullptr)
1480
+ return false;
1481
+ ...
1482
+ }
1483
+ ```
1484
+
1485
+ Querying the type of an object at run-time frequently means a design problem. Needing to know the type of an object at runtime is often an indication that the design of your class hierarchy is flawed.
1486
+
1487
+ Undisciplined use of RTTI makes code hard to maintain. It can lead to type-based decision trees or switch statements scattered throughout the code, all of which must be examined when making further changes.
1488
+
1489
+ RTTI has legitimate uses but is prone to abuse, so you must be careful when using it. You may use it freely in unit tests, but avoid it when possible in other code. In particular, think twice before using RTTI in new code. If you find yourself needing to write code that behaves differently based on the class of an object, consider one of the following alternatives to querying the type:
1490
+
1491
+ * Virtual methods are the preferred way of executing
1492
+ different code paths depending on a specific subclass
1493
+ type. This puts the work within the object itself.
1494
+ * If the work belongs outside the object and instead
1495
+ in some processing code, consider a double-dispatch
1496
+ solution, such as the Visitor design pattern. This
1497
+ allows a facility outside the object itself to
1498
+ determine the type of class using the built-in type
1499
+ system.
1500
+
1501
+ When the logic of a program guarantees that a given instance of a base class is in fact an instance of a particular derived class, then a `dynamic_cast` may be used freely on the object. Usually one can use a `static_cast` as an alternative in such situations.
1502
+
1503
+ Decision trees based on type are a strong indication that your code is on the wrong track.
1504
+ ```
1505
+ if (typeid(*data) == typeid(D1)) {
1506
+ ...
1507
+ } else if (typeid(*data) == typeid(D2)) {
1508
+ ...
1509
+ } else if (typeid(*data) == typeid(D3)) {
1510
+ ...
1511
+ ```
1512
+
1513
+ Code such as this usually breaks when additional subclasses are added to the class hierarchy. Moreover, when properties of a subclass change, it is difficult to find and modify all the affected code segments.
1514
+
1515
+ Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Moreover, workarounds disguise your true intent.
1516
+
1517
+ ## Casting
1518
+
1519
+ Use C++-style casts like `static_cast<float>(double_value)`, or brace initialization for conversion of arithmetic types like `int64_t y = int64_t{1} << 42`. Do not use cast formats like `(int)x` unless the cast is to `void`. You may use cast formats like `T(x)` only when `T` is a class type.
1520
+
1521
+ C++ introduced a different cast system from C that distinguishes the types of cast operations.
1522
+
1523
+ The problem with C casts is the ambiguity of the operation; sometimes you are doing a *conversion* (e.g., `(int)3.5`) and sometimes you are doing a *cast* (e.g., `(int)"hello"`). Brace initialization and C++ casts can often help avoid this ambiguity. Additionally, C++ casts are more visible when searching for them.
1524
+
1525
+ The C++-style cast syntax is verbose and cumbersome.
1526
+
1527
+ In general, do not use C-style casts. Instead, use these C++-style casts when explicit type conversion is necessary.
1528
+
1529
+ * Use brace initialization to convert arithmetic types
1530
+ (e.g., `int64_t{x}`). This is the safest approach because code
1531
+ will not compile if conversion can result in information loss. The
1532
+ syntax is also concise.
1533
+ * When explicitly converting to a class type, use a function-style cast;
1534
+ e.g., prefer `std::string(some_cord)` to
1535
+ `static_cast<std::string>(some_cord)`.
1536
+ * Use `absl::implicit_cast`
1537
+ to safely cast up a type hierarchy,
1538
+ e.g., casting a `Foo*` to a
1539
+ `SuperclassOfFoo*` or casting a
1540
+ `Foo*` to a `const Foo*`. C++
1541
+ usually does this automatically but some situations
1542
+ need an explicit up-cast, such as use of the
1543
+ `?:` operator.
1544
+ * Use `static_cast` as the equivalent of a C-style cast
1545
+ that does value conversion, when you need to
1546
+ explicitly up-cast a pointer from a class to its superclass, or when
1547
+ you need to explicitly cast a pointer from a superclass to a
1548
+ subclass. In this last case, you must be sure your object is
1549
+ actually an instance of the subclass.
1550
+ * Use `const_cast` to remove the
1551
+ `const` qualifier (see [const](#Use_of_const)).
1552
+ * Use `reinterpret_cast` to do unsafe conversions of
1553
+ pointer types to and from integer and other pointer
1554
+ types,
1555
+ including `void*`. Use this
1556
+ only if you know what you are doing and you understand the aliasing
1557
+ issues. Also, consider dereferencing the pointer (without a cast) and
1558
+ using `std::bit_cast` to cast the resulting value.
1559
+ * Use `std::bit_cast` to interpret the raw bits of a
1560
+ value using a different type of the same size (a type pun), such as
1561
+ interpreting the bits of a `double` as
1562
+ `int64_t`.
1563
+
1564
+ See the [RTTI section](#Run-Time_Type_Information__RTTI_) for guidance on the use of `dynamic_cast`.
1565
+
1566
+ ## Streams
1567
+
1568
+ Use streams where appropriate, and stick to "simple" usages. Overload `<<` for streaming only for types representing values, and write only the user-visible value, not any implementation details.
1569
+
1570
+ Streams are the standard I/O abstraction in C++, as exemplified by the standard header `<iostream>`. They are widely used in Google code, mostly for debug logging and test diagnostics.
1571
+
1572
+ The `<<` and `>>` stream operators provide an API for formatted I/O that is easily learned, portable, reusable, and extensible. `printf`, by contrast, doesn't even support `std::string`, to say nothing of user-defined types, and is very difficult to use portably. `printf` also obliges you to choose among the numerous slightly different versions of that function, and navigate the dozens of conversion specifiers.
1573
+
1574
+ Streams provide first-class support for console I/O via `std::cin`, `std::cout`, `std::cerr`, and `std::clog`. The C APIs do as well, but are hampered by the need to manually buffer the input.
1575
+
1576
+ * Stream formatting can be configured by mutating the
1577
+ state of the stream. Such mutations are persistent, so
1578
+ the behavior of your code can be affected by the entire
1579
+ previous history of the stream, unless you go out of your
1580
+ way to restore it to a known state every time other code
1581
+ might have touched it. User code can not only modify the
1582
+ built-in state, it can add new state variables and behaviors
1583
+ through a registration system.
1584
+ * It is difficult to precisely control stream output, due
1585
+ to the above issues, the way code and data are mixed in
1586
+ streaming code, and the use of operator overloading (which
1587
+ may select a different overload than you expect).
1588
+ * The practice of building up output through chains
1589
+ of `<<` operators interferes with
1590
+ internationalization, because it bakes word order into the
1591
+ code, and streams' support for localization is [flawed](http://www.boost.org/doc/libs/1_48_0/libs/locale/doc/html/rationale.html#rationale_why).
1592
+ * The streams API is subtle and complex, so programmers must
1593
+ develop experience with it in order to use it effectively.
1594
+ * Resolving the many overloads of `<<` is
1595
+ extremely costly for the compiler. When used pervasively in a
1596
+ large codebase, it can consume as much as 20% of the parsing
1597
+ and semantic analysis time.
1598
+
1599
+ Use streams only when they are the best tool for the job. This is typically the case when the I/O is ad-hoc, local, human-readable, and targeted at other developers rather than end-users. Be consistent with the code around you, and with the codebase as a whole; if there's an established tool for your problem, use that tool instead. In particular, logging libraries are usually a better choice than `std::cerr` or `std::clog` for diagnostic output, and the libraries in `absl/strings` or the equivalent are usually a better choice than `std::stringstream`.
1600
+
1601
+ Avoid using streams for I/O that faces external users or handles untrusted data. Instead, find and use the appropriate templating libraries to handle issues like internationalization, localization, and security hardening.
1602
+
1603
+ If you do use streams, avoid the stateful parts of the streams API (other than error state), such as `imbue()`, `xalloc()`, and `register_callback()`. Use explicit formatting functions (such as `absl::StreamFormat()`) rather than stream manipulators or formatting flags to control formatting details such as number base, precision, or padding.
1604
+
1605
+ Overload `<<` as a streaming operator for your type only if your type represents a value, and `<<` writes out a human-readable string representation of that value. Avoid exposing implementation details in the output of `<<`; if you need to print object internals for debugging, use named functions instead (a method named `DebugString()` is the most common convention).
1606
+
1607
+ ## Preincrement and Predecrement
1608
+
1609
+ Use the prefix form (`++i`) of the increment and decrement operators unless you need postfix semantics.
1610
+
1611
+ When a variable is incremented (`++i` or `i++`) or decremented (`--i` or `i--`) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement).
1612
+
1613
+ A postfix increment/decrement expression evaluates to the value *as it was before it was modified*. This can result in code that is more compact but harder to read. The prefix form is generally more readable, is never less efficient, and can be more efficient because it doesn't need to make a copy of the value as it was before the operation.
1614
+
1615
+ The tradition developed, in C, of using post-increment, even when the expression value is not used, especially in `for` loops.
1616
+
1617
+ Use prefix increment/decrement, unless the code explicitly needs the result of the postfix increment/decrement expression.
1618
+
1619
+ ## Use of const
1620
+
1621
+ In APIs, use `const` whenever it makes sense. `constexpr` is a better choice for some uses of `const`.
1622
+
1623
+ Declared variables and parameters can be preceded by the keyword `const` to indicate the variables are not changed (e.g., `const int foo`). Class functions can have the `const` qualifier to indicate the function does not change the state of the class member variables (e.g., `class Foo { int Bar(char c) const; };`).
1624
+
1625
+ Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs.
1626
+
1627
+ `const` is viral: if you pass a `const` variable to a function, that function must have `const` in its prototype (or the variable will need a `const_cast`). This can be a particular problem when calling library functions.
1628
+
1629
+ We strongly recommend using `const` in APIs (i.e., on function parameters, methods, and non-local variables) wherever it is meaningful and accurate. This provides consistent, mostly compiler-verified documentation of what objects an operation can mutate. Having a consistent and reliable way to distinguish reads from writes is critical to writing thread-safe code, and is useful in many other contexts as well. In particular:
1630
+
1631
+ * If a function guarantees that it will not modify an argument
1632
+ passed by reference or by pointer, the corresponding function parameter
1633
+ should be a reference-to-const (`const T&`) or
1634
+ pointer-to-const (`const T*`), respectively.
1635
+ * For a function parameter passed by value, `const` has
1636
+ no effect on the caller, thus is not recommended in function
1637
+ declarations. See [TotW #109](https://abseil.io/tips/109).
1638
+ * Declare methods to be `const` unless they
1639
+ alter the logical state of the object (or enable the user to modify
1640
+ that state, e.g., by returning a non-`const` reference, but that's
1641
+ rare), or they can't safely be invoked concurrently.
1642
+
1643
+ Using `const` on local variables is neither encouraged nor discouraged.
1644
+
1645
+ All of a class's `const` operations should be safe to invoke concurrently with each other. If that's not feasible, the class must be clearly documented as "thread-unsafe".
1646
+
1647
+ **WHERE TO PUT THE CONST**
1648
+
1649
+ Some people favor the form `int const* foo` to `const int* foo`. They argue that this is more readable because it's more consistent: it keeps the rule that `const` always follows the object it's describing. However, this consistency argument doesn't apply in codebases with few deeply-nested pointer expressions since most `const` expressions have only one `const`, and it applies to the underlying value. In such cases, there's no consistency to maintain. Putting the `const` first is arguably more readable, since it follows English in putting the "adjective" (`const`) before the "noun" (`int`).
1650
+
1651
+ That said, while we encourage putting `const` first, we do not require it. But be consistent with the code around you!
1652
+
1653
+ ## Use of constexpr, constinit, and consteval
1654
+
1655
+ Use `constexpr` to define true constants or to ensure constant initialization. Use `constinit` to ensure constant initialization for non-constant variables.
1656
+
1657
+ Some variables can be declared `constexpr` to indicate the variables are true constants, i.e., fixed at compilation/link time. Some functions and constructors can be declared `constexpr` which enables them to be used in defining a `constexpr` variable. Functions can be declared `consteval` to restrict their use to compile time.
1658
+
1659
+ Use of `constexpr` enables definition of constants with floating-point expressions rather than just literals; definition of constants of user-defined types; and definition of constants with function calls.
1660
+
1661
+ Prematurely marking something as `constexpr` may cause migration problems if later on it has to be downgraded. Current restrictions on what is allowed in `constexpr` functions and constructors may invite obscure workarounds in these definitions.
1662
+
1663
+ `constexpr` definitions enable a more robust specification of the constant parts of an interface. Use `constexpr` to specify true constants and the functions that support their definitions. `consteval` may be used for code that must not be invoked at runtime. Avoid complexifying function definitions to enable their use with `constexpr`. Do not use `constexpr` or `consteval` to force inlining.
1664
+
1665
+ ## Integer Types
1666
+
1667
+ Of the built-in C++ integer types, the only one used is `int`. If a program needs an integer type of a different size, use an exact-width integer type from `<stdint.h>`, such as `int16_t`. If you have a value that could ever be greater than or equal to 2^31, use a 64-bit type such as `int64_t`. Keep in mind that even if your value won't ever be too large for an `int`, it may be used in intermediate calculations which may require a larger type. When in doubt, choose a larger type.
1668
+
1669
+ C++ does not specify exact sizes for the integer types like `int`. Common sizes on contemporary architectures are 16 bits for `short`, 32 bits for `int`, 32 or 64 bits for `long`, and 64 bits for `long long`, but different platforms make different choices, in particular for `long`.
1670
+
1671
+ Uniformity of declaration.
1672
+
1673
+ The sizes of integral types in C++ can vary based on compiler and architecture.
1674
+
1675
+ The standard library header `<stdint.h>` defines types like `int16_t`, `uint32_t`, `int64_t`, etc. You should always use those in preference to `short`, `unsigned long long`, and the like, when you need a guarantee on the size of an integer. Prefer to omit the `std::` prefix for these types, as the extra 5 characters do not merit the added clutter. Of the built-in integer types, only `int` should be used. When appropriate, you are welcome to use standard type aliases like `size_t` and `ptrdiff_t`.
1676
+
1677
+ We use `int` very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old `int` for such things. You should assume that an `int` is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use `int64_t` or `uint64_t`.
1678
+
1679
+ For integers we know can be "big", use `int64_t`.
1680
+
1681
+ You should not use the unsigned integer types such as `uint32_t`, unless there is a valid reason such as representing a bit pattern rather than a number, or you need defined overflow modulo 2^N. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this.
1682
+
1683
+ If your code is a container that returns a size, be sure to use a type that will accommodate any possible usage of your container. When in doubt, use a larger type rather than a smaller type.
1684
+
1685
+ Use care when converting integer types. Integer conversions and promotions can cause undefined behavior, leading to security bugs and other problems.
1686
+
1687
+ **ON UNSIGNED INTEGERS**
1688
+
1689
+ Unsigned integers are good for representing bitfields and modular arithmetic. Because of historical accident, the C++ standard also uses unsigned integers to represent the size of containers - many members of the standards body believe this to be a mistake, but it is effectively impossible to fix at this point. The fact that unsigned arithmetic doesn't model the behavior of a simple integer, but is instead defined by the standard to model modular arithmetic (wrapping around on overflow/underflow), means that a significant class of bugs cannot be diagnosed by the compiler. In other cases, the defined behavior impedes optimization.
1690
+
1691
+ That said, mixing signedness of integer types is responsible for an equally large class of problems. The best advice we can provide: try to use iterators and containers rather than pointers and sizes, try not to mix signedness, and try to avoid unsigned types (except for representing bitfields or modular arithmetic). Do not use an unsigned type merely to assert that a variable is non-negative.
1692
+
1693
+ ## Floating-Point Types
1694
+
1695
+ Of the built-in C++ floating-point types, the only ones used are `float` and `double`. You may assume that these types represent IEEE-754 binary32 and binary64, respectively.
1696
+
1697
+ Do not use `long double`, as it gives non-portable results.
1698
+
1699
+ ## Architecture Portability
1700
+
1701
+ Write architecture-portable code. Do not rely on CPU features specific to a single processor.
1702
+
1703
+ * When printing values, use type-safe numeric formatting libraries like
1704
+ [`absl::StrCat`](https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_cat.h),
1705
+ [`absl::Substitute`](https://github.com/abseil/abseil-cpp/blob/master/absl/strings/substitute.h),
1706
+ [`absl::StrFormat`](https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_format.h),
1707
+ or [`std::ostream`](#Streams) instead of the
1708
+ `printf` family of functions.
1709
+ * When moving structured data into or out of your process, encode it using a
1710
+ serialization library like
1711
+ [Protocol
1712
+ Buffers](https://protobuf.dev/) rather than copying the in-memory representation around.
1713
+ * If you need to work with memory addresses as integers, store them in
1714
+ `uintptr_t`s rather than `uint32_t`s or
1715
+ `uint64_t`s.
1716
+ * Use [braced-initialization](#Casting) as needed to create
1717
+ 64-bit constants. For example:
1718
+ ```
1719
+ int64_t my_value{0x123456789};
1720
+ uint64_t my_mask{uint64_t{3} << 48};
1721
+ ```
1722
+ * Use portable [floating point types](#Floating-Point_Types);
1723
+ avoid `long double`.
1724
+ * Use portable [integer types](#Integer_Types); avoid
1725
+ `short`, `long`, and `long long`.
1726
+
1727
+ ## Preprocessor Macros
1728
+
1729
+ Avoid defining macros, especially in headers; prefer inline functions, enums, and `const` variables. Name macros with a project-specific prefix. Do not use macros to define pieces of a C++ API.
1730
+
1731
+ Macros mean that the code you see is not the same as the code the compiler sees. This can introduce unexpected behavior, especially since macros have global scope.
1732
+
1733
+ The problems introduced by macros are especially severe when they are used to define pieces of a C++ API, and still more so for public APIs. Every error message from the compiler when developers incorrectly use that interface now must explain how the macros formed the interface. Refactoring and analysis tools have a dramatically harder time updating the interface. As a consequence, we specifically disallow using macros in this way. For example, avoid patterns like:
1734
+ ```
1735
+ class WOMBAT_TYPE(Foo) {
1736
+ // ...
1737
+
1738
+ public:
1739
+ EXPAND_PUBLIC_WOMBAT_API(Foo)
1740
+
1741
+ EXPAND_WOMBAT_COMPARISONS(Foo, ==, <)
1742
+ };
1743
+ ```
1744
+
1745
+ Luckily, macros are not nearly as necessary in C++ as they are in C. Instead of using a macro to inline performance-critical code, use an inline function. Instead of using a macro to store a constant, use a `const` variable. Instead of using a macro to "abbreviate" a long variable name, use a reference. Instead of using a macro to conditionally compile code ... well, don't do that at all (except, of course, for the `#define` guards to prevent double inclusion of header files). It makes testing much more difficult.
1746
+
1747
+ Macros can do things these other techniques cannot, and you do see them in the codebase, especially in the lower-level libraries. And some of their special features (like stringifying, concatenation, and so forth) are not available through the language proper. But before using a macro, consider carefully whether there's a non-macro way to achieve the same result. If you need to use a macro to define an interface, contact your project leads to request a waiver of this rule.
1748
+
1749
+ The following usage pattern will avoid many problems with macros; if you use macros, follow it whenever possible:
1750
+
1751
+ * Don't define macros in a `.h` file.
1752
+ * `#define` macros right before you use
1753
+ them, and `#undef` them right after.
1754
+ * Do not just `#undef` an existing macro
1755
+ before replacing it with your own; instead, pick a name
1756
+ that's likely to be unique.
1757
+ * Try not to use macros that expand to unbalanced C++
1758
+ constructs, or at least document that behavior
1759
+ well.
1760
+ * Prefer not using `##` to generate
1761
+ function/class/variable names.
1762
+
1763
+ Exporting macros from headers (i.e., defining them in a header without `#undef`ing them before the end of the header) is extremely strongly discouraged. If you do export a macro from a header, it must have a globally unique name. To achieve this, it must be named with a prefix consisting of your project's namespace name (but upper case).
1764
+
1765
+ ## 0 and nullptr/NULL
1766
+
1767
+ Use `nullptr` for pointers, and `'\0'` for chars (and not the `0` literal).
1768
+
1769
+ For pointers (address values), use `nullptr`, as this provides type-safety.
1770
+
1771
+ Use `'\0'` for the null character. Using the correct type makes the code more readable.
1772
+
1773
+ ## sizeof
1774
+
1775
+ Prefer `sizeof(varname)` to `sizeof(type)`.
1776
+
1777
+ Use `sizeof(varname)` when you take the size of a particular variable. `sizeof(varname)` will update appropriately if someone changes the variable type either now or later. You may use `sizeof(type)` for code unrelated to any particular variable, such as code that manages an external or internal data format where a variable of an appropriate C++ type is not convenient.
1778
+ ```
1779
+ MyStruct data;
1780
+ memset(&data, 0, sizeof(data));
1781
+ ```
1782
+
1783
+ ```
1784
+ memset(&data, 0, sizeof(MyStruct));
1785
+ ```
1786
+
1787
+ ```
1788
+ if (raw_size < sizeof(int)) {
1789
+ LOG(ERROR) << "compressed record not big enough for count: " << raw_size;
1790
+ return false;
1791
+ }
1792
+ ```
1793
+
1794
+ ## Type Deduction (including auto)
1795
+
1796
+ Use type deduction only if it makes the code clearer to readers who aren't familiar with the project, or if it makes the code safer. Do not use it merely to avoid the inconvenience of writing an explicit type.
1797
+
1798
+ There are several contexts in which C++ allows (or even requires) types to be deduced by the compiler, rather than spelled out explicitly in the code:
1799
+
1800
+ [Function template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction) : A function template can be invoked without explicit template arguments. The compiler deduces those arguments from the types of the function arguments:
1801
+
1802
+ ```
1803
+ template <typename T>
1804
+ void f(T t);
1805
+
1806
+ f(0); // Invokes f<int>(0)
1807
+ ```
1808
+
1809
+ [`auto` variable declarations](https://en.cppreference.com/w/cpp/language/auto) : A variable declaration can use the `auto` keyword in place of the type. The compiler deduces the type from the variable's initializer, following the same rules as function template argument deduction with the same initializer (so long as you don't use curly braces instead of parentheses).
1810
+
1811
+ ```
1812
+ auto a = 42; // a is an int
1813
+ auto& b = a; // b is an int&
1814
+ auto c = b; // c is an int
1815
+ auto d{42}; // d is an int, not a std::initializer_list<int>
1816
+ ```
1817
+
1818
+ `auto` can be qualified with `const`, and can be
1819
+ used as part of a pointer or reference type, and (since C++17) as a
1820
+ non-type template argument. A rare variant of this syntax uses
1821
+ `decltype(auto)` instead of `auto`, in which case
1822
+ the deduced type is the result of applying
1823
+ [`decltype`](https://en.cppreference.com/w/cpp/language/decltype)
1824
+ to the initializer.
1825
+
1826
+ [Function return type deduction](https://en.cppreference.com/w/cpp/language/function#Return_type_deduction) : `auto` (and `decltype(auto)`) can also be used in place of a function return type. The compiler deduces the return type from the `return` statements in the function body, following the same rules as for variable declarations:
1827
+
1828
+ ```
1829
+ auto f() { return 0; } // The return type of f is int
1830
+ ```
1831
+
1832
+ [Lambda expression](#Lambda_expressions) return types can be
1833
+ deduced in the same way, but this is triggered by omitting the return type,
1834
+ rather than by an explicit `auto`. Confusingly,
1835
+ [trailing return type](#trailing_return) syntax for functions
1836
+ also uses `auto` in the return-type position, but that doesn't
1837
+ rely on type deduction; it's just an alternative syntax for an explicit
1838
+ return type.
1839
+
1840
+ [Generic lambdas](https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas) : A lambda expression can use the `auto` keyword in place of one or more of its parameter types. This causes the lambda's call operator to be a function template instead of an ordinary function, with a separate template parameter for each `auto` function parameter:
1841
+
1842
+ ```
1843
+ // Sort `vec` in decreasing order
1844
+ std::sort(vec.begin(), vec.end(), [](auto lhs, auto rhs) { return lhs > rhs; });
1845
+ ```
1846
+
1847
+ [Lambda init captures](https://isocpp.org/wiki/faq/cpp14-language#lambda-captures) : Lambda captures can have explicit initializers, which can be used to declare wholly new variables rather than only capturing existing ones:
1848
+
1849
+ ```
1850
+ [x = 42, y = "foo"] { ... } // x is an int, and y is a const char*
1851
+ ```
1852
+
1853
+ This syntax doesn't allow the type to be specified; instead, it's deduced
1854
+ using the rules for `auto` variables.
1855
+
1856
+ [Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction) : See [below](#CTAD).
1857
+
1858
+ [Structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) : When declaring a tuple, struct, or array using `auto`, you can specify names for the individual elements instead of a name for the whole object; these names are called "structured bindings", and the whole declaration is called a "structured binding declaration". This syntax provides no way of specifying the type of either the enclosing object or the individual names:
1859
+
1860
+ ```
1861
+ auto [iter, success] = my_map.insert({key, value});
1862
+ if (!success) {
1863
+ iter->second = value;
1864
+ }
1865
+ ```
1866
+
1867
+ The `auto` can also be qualified with `const`,
1868
+ `&`, and `&&`, but note that these qualifiers
1869
+ technically apply to the anonymous tuple/struct/array, rather than the
1870
+ individual bindings. The rules that determine the types of the bindings
1871
+ are quite complex; the results tend to be unsurprising, except that
1872
+ the binding types typically won't be references even if the declaration
1873
+ declares a reference (but they will usually behave like references anyway).
1874
+
1875
+ (These summaries omit many details and caveats; see the links for further information.)
1876
+
1877
+ * C++ type names can be long and cumbersome, especially when they
1878
+ involve templates or namespaces.
1879
+ * When a C++ type name is repeated within a single declaration or a
1880
+ small code region, the repetition may not be aiding readability.
1881
+ * It is sometimes safer to let the type be deduced, since that avoids
1882
+ the possibility of unintended copies or type conversions.
1883
+
1884
+ C++ code is usually clearer when types are explicit, especially when type deduction would depend on information from distant parts of the code. In expressions like:
1885
+ ```
1886
+ auto foo = x.add_foo();
1887
+ auto i = y.Find(key);
1888
+ ```
1889
+
1890
+ it may not be obvious what the resulting types are if the type of `y` isn't very well known, or if `y` was declared many lines earlier.
1891
+
1892
+ Programmers have to understand when type deduction will or won't produce a reference type, or they'll get copies when they didn't mean to.
1893
+
1894
+ If a deduced type is used as part of an interface, then a programmer might change its type while only intending to change its value, leading to a more radical API change than intended.
1895
+
1896
+ The fundamental rule is: use type deduction only to make the code clearer or safer, and do not use it merely to avoid the inconvenience of writing an explicit type. When judging whether the code is clearer, keep in mind that your readers are not necessarily on your team, or familiar with your project, so types that you and your reviewer experience as unnecessary clutter will very often provide useful information to others. For example, you can assume that the return type of `make_unique<Foo>()` is obvious, but the return type of `MyWidgetFactory()` probably isn't.
1897
+
1898
+ These principles apply to all forms of type deduction, but the details vary, as described in the following sections.
1899
+
1900
+ **FUNCTION TEMPLATE ARGUMENT DEDUCTION**
1901
+
1902
+ Function template argument deduction is almost always OK. Type deduction is the expected default way of interacting with function templates, because it allows function templates to act like infinite sets of ordinary function overloads. Consequently, function templates are almost always designed so that template argument deduction is clear and safe, or doesn't compile.
1903
+
1904
+ **LOCAL VARIABLE TYPE DEDUCTION**
1905
+
1906
+ For local variables, you can use type deduction to make the code clearer by eliminating type information that is obvious or irrelevant, so that the reader can focus on the meaningful parts of the code:
1907
+ ```
1908
+ std::unique_ptr<WidgetWithBellsAndWhistles> widget =
1909
+ std::make_unique<WidgetWithBellsAndWhistles>(arg1, arg2);
1910
+ absl::flat_hash_map<std::string,
1911
+ std::unique_ptr<WidgetWithBellsAndWhistles>>::const_iterator
1912
+ it = my_map_.find(key);
1913
+ std::array<int, 6> numbers = {4, 8, 15, 16, 23, 42};
1914
+ ```
1915
+
1916
+ ```
1917
+ auto widget = std::make_unique<WidgetWithBellsAndWhistles>(arg1, arg2);
1918
+ auto it = my_map_.find(key);
1919
+ std::array numbers = {4, 8, 15, 16, 23, 42};
1920
+ ```
1921
+
1922
+ Types sometimes contain a mixture of useful information and boilerplate, such as `it` in the example above: it's obvious that the type is an iterator, and in many contexts the container type and even the key type aren't relevant, but the type of the values is probably useful. In such situations, it's often possible to define local variables with explicit types that convey the relevant information:
1923
+ ```
1924
+ if (auto it = my_map_.find(key); it != my_map_.end()) {
1925
+ WidgetWithBellsAndWhistles& widget = *it->second;
1926
+ // Do stuff with `widget`
1927
+ }
1928
+ ```
1929
+
1930
+ If the type is a template instance, and the parameters are boilerplate but the template itself is informative, you can use class template argument deduction to suppress the boilerplate. However, cases where this actually provides a meaningful benefit are quite rare. Note that class template argument deduction is also subject to a [separate style rule](#CTAD).
1931
+
1932
+ Do not use `decltype(auto)` if a simpler option will work; because it's a fairly obscure feature, it has a high cost in code clarity.
1933
+
1934
+ **RETURN TYPE DEDUCTION**
1935
+
1936
+ Use return type deduction (for both functions and lambdas) only if the function body has a very small number of `return` statements, and very little other code, because otherwise the reader may not be able to tell at a glance what the return type is. Furthermore, use it only if the function or lambda has a very narrow scope, because functions with deduced return types don't define abstraction boundaries: the implementation *is* the interface. In particular, public functions in header files should almost never have deduced return types.
1937
+
1938
+ **PARAMETER TYPE DEDUCTION**
1939
+
1940
+ `auto` parameter types for lambdas should be used with caution, because the actual type is determined by the code that calls the lambda, rather than by the definition of the lambda. Consequently, an explicit type will almost always be clearer unless the lambda is explicitly called very close to where it's defined (so that the reader can easily see both), or the lambda is passed to an interface so well-known that it's obvious what arguments it will eventually be called with (e.g., the `std::sort` example above).
1941
+
1942
+ **LAMBDA INIT CAPTURES**
1943
+
1944
+ Init captures are covered by a [more specific style rule](#Lambda_expressions), which largely supersedes the general rules for type deduction.
1945
+
1946
+ **STRUCTURED BINDINGS**
1947
+
1948
+ Unlike other forms of type deduction, structured bindings can actually give the reader additional information, by giving meaningful names to the elements of a larger object. This means that a structured binding declaration may provide a net readability improvement over an explicit type, even in cases where `auto` would not. Structured bindings are especially beneficial when the object is a pair or tuple (as in the `insert` example above), because they don't have meaningful field names to begin with, but note that you generally [shouldn't use pairs or tuples](#Structs_vs._Tuples) unless a pre-existing API like `insert` forces you to.
1949
+
1950
+ If the object being bound is a struct, it may sometimes be helpful to provide names that are more specific to your usage, but keep in mind that this may also mean the names are less recognizable to your reader than the field names. We recommend using a comment to indicate the name of the underlying field, if it doesn't match the name of the binding, using the same syntax as for function parameter comments:
1951
+ ```
1952
+ auto [/*field_name1=*/bound_name1, /*field_name2=*/bound_name2] = ...
1953
+ ```
1954
+
1955
+ As with function parameter comments, this can enable tools to detect if you get the order of the fields wrong.
1956
+
1957
+ ## Class Template Argument Deduction
1958
+
1959
+ Use class template argument deduction only with templates that have explicitly opted into supporting it.
1960
+
1961
+ [Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction) (often abbreviated "CTAD") occurs when a variable is declared with a type that names a template, and the template argument list is not provided (not even empty angle brackets):
1962
+ ```
1963
+ std::array a = {1, 2, 3}; // `a` is a std::array<int, 3>
1964
+ ```
1965
+
1966
+ The compiler deduces the arguments from the initializer using the template's "deduction guides", which can be explicit or implicit.
1967
+
1968
+ Explicit deduction guides look like function declarations with trailing return types, except that there's no leading `auto`, and the function name is the name of the template. For example, the above example relies on this deduction guide for `std::array`:
1969
+ ```
1970
+ namespace std {
1971
+ template <class T, class... U>
1972
+ array(T, U...) -> std::array<T, 1 + sizeof...(U)>;
1973
+ }
1974
+ ```
1975
+
1976
+ Constructors in a primary template (as opposed to a template specialization) also implicitly define deduction guides.
1977
+
1978
+ When you declare a variable that relies on CTAD, the compiler selects a deduction guide using the rules of constructor overload resolution, and that guide's return type becomes the type of the variable.
1979
+
1980
+ CTAD can sometimes allow you to omit boilerplate from your code.
1981
+
1982
+ The implicit deduction guides that are generated from constructors may have undesirable behavior, or be outright incorrect. This is particularly problematic for constructors written before CTAD was introduced in C++17, because the authors of those constructors had no way of knowing about (much less fixing) any problems that their constructors would cause for CTAD. Furthermore, adding explicit deduction guides to fix those problems might break any existing code that relies on the implicit deduction guides.
1983
+
1984
+ CTAD also suffers from many of the same drawbacks as `auto`, because they are both mechanisms for deducing all or part of a variable's type from its initializer. CTAD does give the reader more information than `auto`, but it also doesn't give the reader an obvious cue that information has been omitted.
1985
+
1986
+ Do not use CTAD with a given template unless the template's maintainers have opted into supporting use of CTAD by providing at least one explicit deduction guide (all templates in the `std` namespace are also presumed to have opted in). This should be enforced with a compiler warning if available.
1987
+
1988
+ Uses of CTAD must also follow the general rules on [Type deduction](#Type_deduction).
1989
+
1990
+ ## Designated Initializers
1991
+
1992
+ Use designated initializers only in their C++20-compliant form.
1993
+
1994
+ [Designated initializers](https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers) are a syntax that allows for initializing an aggregate ("plain old struct") by naming its fields explicitly:
1995
+ ```
1996
+ struct Point {
1997
+ float x = 0.0;
1998
+ float y = 0.0;
1999
+ float z = 0.0;
2000
+ };
2001
+
2002
+ Point p = {
2003
+ .x = 1.0,
2004
+ .y = 2.0,
2005
+ // z will be 0.0
2006
+ };
2007
+ ```
2008
+
2009
+ The explicitly listed fields will be initialized as specified, and others will be initialized in the same way they would be in a traditional aggregate initialization expression like `Point{1.0, 2.0}`.
2010
+
2011
+ Designated initializers can make for convenient and highly readable aggregate expressions, especially for structs with less straightforward ordering of fields than the `Point` example above.
2012
+
2013
+ While designated initializers have long been part of the C standard and supported by C++ compilers as an extension, they were not supported by C++ prior to C++20.
2014
+
2015
+ The rules in the C++ standard are stricter than in C and compiler extensions, requiring that the designated initializers appear in the same order as the fields appear in the struct definition. So in the example above, it is legal according to C++20 to initialize `x` and then `z`, but not `y` and then `x`.
2016
+
2017
+ Use designated initializers only in the form that is compatible with the C++20 standard: with initializers in the same order as the corresponding fields appear in the struct definition.
2018
+
2019
+ ## Lambda Expressions
2020
+
2021
+ Use lambda expressions where appropriate. Prefer explicit captures when the lambda will escape the current scope.
2022
+
2023
+ Lambda expressions are a concise way of creating anonymous function objects. They're often useful when passing functions as arguments. For example:
2024
+ ```
2025
+ std::sort(v.begin(), v.end(), [](int x, int y) {
2026
+ return Weight(x) < Weight(y);
2027
+ });
2028
+ ```
2029
+
2030
+ They further allow capturing variables from the enclosing scope either explicitly by name, or implicitly using a default capture. Explicit captures require each variable to be listed, as either a value or reference capture:
2031
+ ```
2032
+ int weight = 3;
2033
+ int sum = 0;
2034
+ // Captures `weight` by value and `sum` by reference.
2035
+ std::for_each(v.begin(), v.end(), MISSING_LINK {
2036
+ sum += weight * x;
2037
+ });
2038
+ ```
2039
+
2040
+ Default captures implicitly capture any variable referenced in the lambda body, including `this` if any members are used:
2041
+ ```
2042
+ const std::vector<int> lookup_table = ...;
2043
+ std::vector<int> indices = ...;
2044
+ // Captures `lookup_table` by reference, sorts `indices` by the value
2045
+ // of the associated element in `lookup_table`.
2046
+ std::sort(indices.begin(), indices.end(), MISSING_LINK {
2047
+ return lookup_table[a] < lookup_table[b];
2048
+ });
2049
+ ```
2050
+
2051
+ A variable capture can also have an explicit initializer, which can be used for capturing move-only variables by value, or for other situations not handled by ordinary reference or value captures:
2052
+ ```
2053
+ std::unique_ptr<Foo> foo = ...;
2054
+ [foo = std::move(foo)] () {
2055
+ ...
2056
+ }
2057
+ ```
2058
+
2059
+ Such captures (often called "init captures" or "generalized lambda captures") need not actually "capture" anything from the enclosing scope, or even have a name from the enclosing scope; this syntax is a fully general way to define members of a lambda object:
2060
+ ```
2061
+ [foo = std::vector<int>({1, 2, 3})] () {
2062
+ ...
2063
+ }
2064
+ ```
2065
+
2066
+ The type of a capture with an initializer is deduced using the same rules as `auto`.
2067
+
2068
+ * Lambdas are much more concise than other ways of
2069
+ defining function objects to be passed to STL
2070
+ algorithms, which can be a readability
2071
+ improvement.
2072
+ * Appropriate use of default captures can remove
2073
+ redundancy and highlight important exceptions from
2074
+ the default.
2075
+ * Lambdas, `std::function`, and
2076
+ `std::bind` can be used in combination as a
2077
+ general purpose callback mechanism; they make it easy
2078
+ to write functions that take bound functions as
2079
+ arguments.
2080
+
2081
+ * Variable capture in lambdas can be a source of dangling-pointer
2082
+ bugs, particularly if a lambda escapes the current scope.
2083
+ * Default captures by value can be misleading because they do not prevent
2084
+ dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep
2085
+ copy, so it often has the same lifetime issues as capture by reference.
2086
+ This is especially confusing when capturing `this` by value,
2087
+ since the use of `this` is often implicit.
2088
+ * Captures actually declare new variables (whether or not the captures have
2089
+ initializers), but they look nothing like any other variable declaration
2090
+ syntax in C++. In particular, there's no place for the variable's type,
2091
+ or even an `auto` placeholder (although init captures can
2092
+ indicate it indirectly, e.g., with a cast). This can make it difficult to
2093
+ even recognize them as declarations.
2094
+ * Init captures inherently rely on [type
2095
+ deduction](#Type_deduction), and suffer from many of the same drawbacks as
2096
+ `auto`, with the additional problem that the syntax doesn't
2097
+ even cue the reader that deduction is taking place.
2098
+ * It's possible for use of lambdas to get out of
2099
+ hand; very long nested anonymous functions can make
2100
+ code harder to understand.
2101
+
2102
+ * Use lambda expressions where appropriate, with formatting as
2103
+ described [below](#Formatting_Lambda_Expressions).
2104
+ * Prefer explicit captures if the lambda may escape the current scope.
2105
+ For example, instead of:
2106
+ ```
2107
+ {
2108
+ Foo foo;
2109
+ ...
2110
+ executor->Schedule([&] { Frobnicate(foo); })
2111
+ ...
2112
+ }
2113
+ // BAD! The fact that the lambda makes use of a reference to `foo` and
2114
+ // possibly `this` (if `Frobnicate` is a member function) may not be
2115
+ // apparent on a cursory inspection. If the lambda is invoked after
2116
+ // the function returns, that would be bad, because both `foo`
2117
+ // and the enclosing object could have been destroyed.
2118
+ ```
2119
+
2120
+ prefer to write:
2121
+ ```
2122
+ {
2123
+ Foo foo;
2124
+ ...
2125
+ executor->Schedule([&foo] { Frobnicate(foo); })
2126
+ ...
2127
+ }
2128
+ // BETTER - The compile will fail if `Frobnicate` is a member
2129
+ // function, and it's clearer that `foo` is dangerously captured by
2130
+ // reference.
2131
+ ```
2132
+
2133
+ - Use default capture by reference (`[&]`) only when the lifetime of the lambda is obviously shorter than any potential captures.
2134
+ - Use default capture by value (`[=]`) only as a means of binding a few variables for a short lambda, where the set of captured variables is obvious at a glance, and which does not result in capturing `this` implicitly. (That means that a lambda that appears in a non-static class member function and refers to non-static class members in its body must capture `this` explicitly or via `[&]`.) Prefer not to write long or complex lambdas with default capture by value.
2135
+ - Use captures only to actually capture variables from the enclosing scope. Do not use captures with initializers to introduce new names, or to substantially change the meaning of an existing name. Instead, declare a new variable in the conventional way and then capture it, or avoid the lambda shorthand and define a function object explicitly.
2136
+ - See the section on [type deduction](#Type_deduction) for guidance on specifying the parameter and return types.
2137
+
2138
+ ## Template Metaprogramming
2139
+
2140
+ Avoid complicated template programming.
2141
+
2142
+ Template metaprogramming refers to a family of techniques that exploit the fact that the C++ template instantiation mechanism is Turing complete and can be used to perform arbitrary compile-time computation in the type domain.
2143
+
2144
+ Template metaprogramming allows extremely flexible interfaces that are type safe and high performance. Facilities like [GoogleTest](https://github.com/google/googletest), `std::tuple`, `std::function`, and Boost.Spirit would be impossible without it.
2145
+
2146
+ The techniques used in template metaprogramming are often obscure to anyone but language experts. Code that uses templates in complicated ways is often unreadable, and is hard to debug or maintain.
2147
+
2148
+ Template metaprogramming often leads to extremely poor compile time error messages: even if an interface is simple, the complicated implementation details become visible when the user does something wrong.
2149
+
2150
+ Template metaprogramming interferes with large scale refactoring by making the job of refactoring tools harder. First, the template code is expanded in multiple contexts, and it's hard to verify that the transformation makes sense in all of them. Second, some refactoring tools work with an AST that only represents the structure of the code after template expansion. It can be difficult to automatically work back to the original source construct that needs to be rewritten.
2151
+
2152
+ Template metaprogramming sometimes allows cleaner and easier-to-use interfaces than would be possible without it, but it's also often a temptation to be overly clever. It's best used in a small number of low level components where the extra maintenance burden is spread out over a large number of uses.
2153
+
2154
+ Think twice before using template metaprogramming or other complicated template techniques; think about whether the average member of your team will be able to understand your code well enough to maintain it after you switch to another project, or whether a non-C++ programmer or someone casually browsing the codebase will be able to understand the error messages or trace the flow of a function they want to call. If you're using recursive template instantiations or type lists or metafunctions or expression templates, or relying on SFINAE or on the `sizeof` trick for detecting function overload resolution, then there's a good chance you've gone too far.
2155
+
2156
+ If you use template metaprogramming, you should expect to put considerable effort into minimizing and isolating the complexity. You should hide metaprogramming as an implementation detail whenever possible, so that user-facing headers are readable, and you should make sure that tricky code is especially well commented. You should carefully document how the code is used, and you should say something about what the "generated" code looks like. Pay extra attention to the error messages that the compiler emits when users make mistakes. The error messages are part of your user interface, and your code should be tweaked as necessary so that the error messages are understandable and actionable from a user point of view.
2157
+
2158
+ ## Concepts and Constraints
2159
+
2160
+ Use concepts sparingly. In general, concepts and constraints should only be used in cases where templates would have been used prior to C++20. Avoid introducing new concepts in headers, unless the headers are marked as internal to the library. Do not define concepts that are not enforced by the compiler. Prefer constraints over template metaprogramming, and avoid the `template<Concept T>` syntax; instead, use the `requires(Concept<T>)` syntax.
2161
+
2162
+ The `concept` keyword is a new mechanism for defining requirements (such as type traits or interface specifications) for a template parameter. The `requires` keyword provides mechanisms for placing anonymous constraints on templates and verifying that constraints are satisfied at compile time. Concepts and constraints are often used together, but can be also used independently.
2163
+
2164
+ * Concepts allow the compiler to generate much better error
2165
+ messages when templates are involved, which can reduce confusion
2166
+ and significantly improve the development experience.
2167
+ * Concepts can reduce the boilerplate necessary for defining
2168
+ and using compile-time constraints, often increasing the clarity
2169
+ of the resulting code.
2170
+ * Constraints provide some capabilities that are difficult to
2171
+ achieve with templates and SFINAE techniques.
2172
+
2173
+ * As with templates, concepts can make code significantly more
2174
+ complex and difficult to understand.
2175
+ * Concept syntax can be confusing to readers, as concepts
2176
+ appear similar to class types at their usage sites.
2177
+ * Concepts, especially at API boundaries, increase code
2178
+ coupling, rigidity, and ossification.
2179
+ * Concepts and constraints can replicate logic from a function
2180
+ body, resulting in code duplication and increased maintenance
2181
+ costs.
2182
+ * Concepts muddy the source of truth for their underlying
2183
+ contracts, as they are standalone named entities that can be
2184
+ utilized in multiple locations, all of which evolve separately
2185
+ from each other.
2186
+ This can cause the stated and implied requirements to diverge
2187
+ over time.
2188
+ * Concepts and constraints affect overload resolution in novel
2189
+ and non-obvious ways.
2190
+ * As with SFINAE, constraints make it harder to refactor code
2191
+ at scale.
2192
+
2193
+ Predefined concepts in the standard library should be preferred to type traits, when equivalent ones exist. (e.g., if `std::is_integral_v` would have been used before C++20, then `std::integral` should be used in C++20 code.) Similarly, prefer modern constraint syntax (via `requires(Condition)`). Avoid legacy template metaprogramming constructs (such as `std::enable_if<Condition>`) as well as the `template<Concept T>` syntax.
2194
+
2195
+ Do not manually re-implement any existing concepts or traits. For example, use `requires(std::default_initializable<T>)` instead of `requires(requires { T v; })` or the like.
2196
+
2197
+ New `concept` declarations should be rare, and only defined internally within a library, such that they are not exposed at API boundaries. More generally, do not use concepts or constraints in cases where you wouldn't use their legacy template equivalents in C++17.
2198
+
2199
+ Do not define concepts that duplicate the function body, or impose requirements that would be insignificant or obvious from reading the body of the code or the resulting error messages. For example, avoid the following:
2200
+ ```
2201
+ template <typename T> // Bad - redundant with negligible benefit
2202
+ concept Addable = std::copyable<T> && requires(T a, T b) { a + b; };
2203
+ template <Addable T>
2204
+ T Add(T x, T y, T z) { return x + y + z; }
2205
+ ```
2206
+
2207
+ Instead, prefer to leave code as an ordinary template unless you can demonstrate that concepts result in significant improvement for that particular case, such as in the resulting error messages for a deeply nested or non-obvious requirement.
2208
+
2209
+ Concepts should be statically verifiable by the compiler. Do not use any concept whose primary benefits would come from a semantic (or otherwise unenforced) constraint. Requirements that are unenforced at compile time should instead be imposed via other mechanisms such as comments, assertions, or tests.
2210
+
2211
+ ## C++20 modules
2212
+
2213
+ Do not use C++20 Modules.
2214
+
2215
+ C++20 introduces "modules", a new language feature designed as an alternative to textual inclusion of header files. It introduces three new keywords to support this: `module`, `export`, and `import`.
2216
+
2217
+ Modules are a big shift in how C++ is written and compiled, and we are still assessing how they may fit into Google's C++ ecosystem in the future. Furthermore, they are not currently well-supported by our build systems, compilers, and other tooling, and need further exploration as to the best practices when writing and using them.
2218
+
2219
+ ## Coroutines
2220
+
2221
+ Only use C++20 coroutines via libraries that have been approved by your project leads.
2222
+
2223
+ C++20 introduced [coroutines](https://en.cppreference.com/w/cpp/language/coroutines.html): functions that can suspend and resume executing later. They are especially convenient for asynchronous programming, where they can provide substantial improvements over traditional callback-based frameworks.
2224
+
2225
+ Unlike most other programming languages (Kotlin, Rust, TypeScript, etc.), C++ does not provide a concrete implementation of coroutines. Instead, it requires users to implement their own awaitable type (using a [promise type](https://en.cppreference.com/w/cpp/language/coroutines#Promise)) which determines coroutine parameter types, how coroutines are executed, and allows running user-defined code during different stages of their execution.
2226
+
2227
+ * Coroutines can be used to implement safe and efficient libraries suited
2228
+ for specific tasks, such as asynchronous programming.
2229
+ * Coroutines are syntactically almost identical to non-coroutine functions,
2230
+ which can make them substantially more readable than alternatives.
2231
+ * The high degree of customization makes it possible to insert more
2232
+ detailed debugging information into coroutines, compared to
2233
+ alternatives.
2234
+
2235
+ * There is no standard coroutine promise type, and each user-defined
2236
+ implementation is likely going to be unique in some aspect.
2237
+ * Because of load-bearing interactions between the return type, the
2238
+ various customizable hooks in the promise type, and compiler-generated
2239
+ code, coroutine semantics are extremely difficult to deduce from reading
2240
+ user code.
2241
+ * The many customizable aspects of coroutines introduce a large number
2242
+ of pitfalls, especially around dangling references and race
2243
+ conditions.
2244
+
2245
+ In summary, designing a high-quality and interoperable coroutine library requires a large amount of difficult work, careful thought, and extensive documentation.
2246
+
2247
+ Use only coroutine libraries that have been approved for project-wide use by your project leads. Do not roll your own promise or awaitable types.
2248
+
2249
+ ## Boost
2250
+
2251
+ Use only approved libraries from the Boost library collection.
2252
+
2253
+ The [Boost library collection](https://www.boost.org/) is a popular collection of peer-reviewed, free, open-source C++ libraries.
2254
+
2255
+ Boost code is generally very high-quality, is widely portable, and fills many important gaps in the C++ standard library, such as type traits and better binders.
2256
+
2257
+ Some Boost libraries encourage coding practices which can hamper readability, such as metaprogramming and other advanced template techniques, and an excessively "functional" style of programming.
2258
+
2259
+ In order to maintain a high level of readability for all contributors who might read and maintain code, we only allow an approved subset of Boost features. Currently, the following libraries are permitted:
2260
+
2261
+ * [Call Traits](https://www.boost.org/libs/utility/call_traits.htm) from `boost/call_traits.hpp`
2262
+ * [Compressed Pair](https://www.boost.org/libs/utility/compressed_pair.htm) from `boost/compressed_pair.hpp`
2263
+ * [The Boost Graph Library (BGL)](https://www.boost.org/libs/graph/) from `boost/graph`,
2264
+ except serialization (`adj_list_serialize.hpp`) and
2265
+ parallel/distributed algorithms and data structures
2266
+ (`boost/graph/parallel/*` and
2267
+ `boost/graph/distributed/*`).
2268
+ * [Property Map](https://www.boost.org/libs/property_map/) from `boost/property_map`, except
2269
+ parallel/distributed property maps (`boost/property_map/parallel/*`).
2270
+ * [Iterator](https://www.boost.org/libs/iterator/) from `boost/iterator`
2271
+ * The part of [Polygon](https://www.boost.org/libs/polygon/) that deals with Voronoi diagram
2272
+ construction and doesn't depend on the rest of
2273
+ Polygon:
2274
+ `boost/polygon/voronoi_builder.hpp`,
2275
+ `boost/polygon/voronoi_diagram.hpp`, and
2276
+ `boost/polygon/voronoi_geometry_type.hpp`
2277
+ * [Bimap](https://www.boost.org/libs/bimap/) from `boost/bimap`
2278
+ * [Statistical Distributions and Functions](https://www.boost.org/libs/math/doc/html/dist.html) from
2279
+ `boost/math/distributions`
2280
+ * [Special Functions](https://www.boost.org/libs/math/doc/html/special.html) from `boost/math/special_functions`
2281
+ * [Root Finding & Minimization Functions](https://www.boost.org/libs/math/doc/html/root_finding.html) from `boost/math/tools`
2282
+ * [Multi-index](https://www.boost.org/libs/multi_index/) from `boost/multi_index`
2283
+ * [Heap](https://www.boost.org/libs/heap/) from `boost/heap`
2284
+ * The flat containers from
2285
+ [Container](https://www.boost.org/libs/container/):
2286
+ `boost/container/flat_map`, and
2287
+ `boost/container/flat_set`
2288
+ * [Intrusive](https://www.boost.org/libs/intrusive/)
2289
+ from `boost/intrusive`.
2290
+ * [The
2291
+ `boost/sort` library](https://www.boost.org/libs/sort/).
2292
+ * [Preprocessor](https://www.boost.org/libs/preprocessor/)
2293
+ from `boost/preprocessor`.
2294
+
2295
+ We are actively considering adding other Boost features to the list, so this list may be expanded in the future.
2296
+
2297
+ ## Disallowed standard library features
2298
+
2299
+ As with [Boost](#Boost), some modern C++ library functionality encourages coding practices that hamper readability — for example by removing checked redundancy (such as type names) that may be helpful to readers, or by encouraging template metaprogramming. Other extensions duplicate functionality available through existing mechanisms, which may lead to confusion and conversion costs.
2300
+
2301
+ The following C++ standard library features may not be used:
2302
+
2303
+ * Compile-time rational numbers
2304
+ (`<ratio>`), because of concerns that
2305
+ it's tied to a more template-heavy interface
2306
+ style.
2307
+ * The `<cfenv>` and
2308
+ `<fenv.h>` headers, because many
2309
+ compilers do not support those features reliably.
2310
+ * The `<filesystem>` header, which
2311
+ does not have sufficient support for testing, and suffers
2312
+ from inherent security vulnerabilities.
2313
+
2314
+ ## Nonstandard Extensions
2315
+
2316
+ Nonstandard extensions to C++ may not be used unless otherwise specified.
2317
+
2318
+ Compilers support various extensions that are not part of standard C++. Such extensions include GCC's `__attribute__`, intrinsic functions such as `__builtin_prefetch` or SIMD, `#pragma`, inline assembly, `__COUNTER__`, `__PRETTY_FUNCTION__`, compound statement expressions (e.g., `foo = ({ int x; Bar(&x); x })`, variable-length arrays and `alloca()`, and the "[Elvis Operator](https://en.wikipedia.org/wiki/Elvis_operator)" `a?:b`.
2319
+
2320
+ * Nonstandard extensions may provide useful features that do not exist
2321
+ in standard C++.
2322
+ * Important performance guidance to the compiler can only be specified
2323
+ using extensions.
2324
+
2325
+ * Nonstandard extensions do not work in all compilers. Use of nonstandard
2326
+ extensions reduces portability of code.
2327
+ * Even if they are supported in all targeted compilers, the extensions
2328
+ are often not well-specified, and there may be subtle behavior differences
2329
+ between compilers.
2330
+ * Nonstandard extensions add features to the language that a reader must
2331
+ know to understand the code.
2332
+ * Nonstandard extensions require additional work to port across architectures.
2333
+
2334
+ Do not use nonstandard extensions. You may use portability wrappers that are implemented using nonstandard extensions, so long as those wrappers are provided by a designated project-wide portability header.
2335
+
2336
+ ## Aliases
2337
+
2338
+ Public aliases are for the benefit of an API's user, and should be clearly documented.
2339
+
2340
+ There are several ways to create names that are aliases of other entities:
2341
+ ```
2342
+ using Bar = Foo;
2343
+ typedef Foo Bar; // But prefer `using` in C++ code.
2344
+ using ::other_namespace::Foo;
2345
+ using enum MyEnumType; // Creates aliases for all enumerators in MyEnumType.
2346
+ ```
2347
+
2348
+ In new code, `using` is preferable to `typedef`, because it provides a more consistent syntax with the rest of C++ and works with templates.
2349
+
2350
+ Like other declarations, aliases declared in a header file are part of that header's public API unless they're in a function definition, in the private portion of a class, or in an explicitly-marked internal namespace. Aliases in such areas or in `.cc` files are implementation details (because client code can't refer to them), and are not restricted by this rule.
2351
+
2352
+ * Aliases can improve readability by simplifying a long or complicated name.
2353
+ * Aliases can reduce duplication by naming in one place a type used repeatedly in an API,
2354
+ which *might* make it easier to change the type later.
2355
+
2356
+ * When placed in a header where client code can refer to them, aliases increase the
2357
+ number of entities in that header's API, increasing its complexity.
2358
+ * Clients can easily rely on unintended details of public aliases, making
2359
+ changes difficult.
2360
+ * It can be tempting to create a public alias that is only intended for use
2361
+ in the implementation, without considering its impact on the API, or on maintainability.
2362
+ * Aliases can create risk of name collisions.
2363
+ * Aliases can reduce readability by giving a familiar construct an unfamiliar name.
2364
+ * Type aliases can create an unclear API contract:
2365
+ it is unclear whether the alias is guaranteed to be identical to the type it aliases,
2366
+ to have the same API, or only to be usable in specified narrow ways.
2367
+
2368
+ Don't put an alias in your public API just to save typing in the implementation; do so only if you intend it to be used by your clients.
2369
+
2370
+ When defining a public alias, document the intent of the new name, including whether it is guaranteed to always be the same as the type it's currently aliased to, or whether a more limited compatibility is intended. This lets the user know whether they can treat the types as substitutable or whether more specific rules must be followed, and can help the implementation retain some degree of freedom to change the alias.
2371
+
2372
+ Don't put namespace aliases in your public API. (See also [Namespaces](#Namespaces).)
2373
+
2374
+ For example, these aliases document how they are intended to be used in client code:
2375
+ ```
2376
+ namespace mynamespace {
2377
+ // Used to store field measurements. DataPoint may change from Bar* to some internal type.
2378
+ // Client code should treat it as an opaque pointer.
2379
+ using DataPoint = ::foo::Bar*;
2380
+
2381
+ // A set of measurements. Just an alias for user convenience.
2382
+ using TimeSeries = std::unordered_set<DataPoint, std::hash<DataPoint>, DataPointComparator>;
2383
+ } // namespace mynamespace
2384
+ ```
2385
+
2386
+ These aliases don't document intended use, and half of them aren't meant for client use:
2387
+ ```
2388
+ namespace mynamespace {
2389
+ // Bad: none of these say how they should be used.
2390
+ using DataPoint = ::foo::Bar*;
2391
+ using ::std::unordered_set; // Bad: just for local convenience
2392
+ using ::std::hash; // Bad: just for local convenience
2393
+ typedef unordered_set<DataPoint, hash<DataPoint>, DataPointComparator> TimeSeries;
2394
+ } // namespace mynamespace
2395
+ ```
2396
+
2397
+ However, local convenience aliases are fine in function definitions, `private` sections of classes, explicitly-marked internal namespaces, and in `.cc` files:
2398
+ ```
2399
+ // In a .cc file
2400
+ using ::foo::Bar;
2401
+ ```
2402
+
2403
+ ## Switch Statements
2404
+
2405
+ If not conditional on an enumerated value, switch statements should always have a `default` case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never execute, treat this as an error. For example:
2406
+ ```
2407
+ switch (var) {
2408
+ case 0: {
2409
+ ...
2410
+ break;
2411
+ }
2412
+ case 1: {
2413
+ ...
2414
+ break;
2415
+ }
2416
+ default: {
2417
+ LOG(FATAL) << "Invalid value in switch statement: " << var;
2418
+ }
2419
+ }
2420
+ ```
2421
+
2422
+ Fall-through from one case label to another must be annotated using the `[[fallthrough]];` attribute. `[[fallthrough]];` should be placed at a point of execution where a fall-through to the next case label occurs. A common exception is consecutive case labels without intervening code, in which case no annotation is needed.
2423
+ ```
2424
+ switch (x) {
2425
+ case 41: // No annotation needed here.
2426
+ case 43:
2427
+ if (dont_be_picky) {
2428
+ // Use this instead of or along with annotations in comments.
2429
+ [[fallthrough]];
2430
+ } else {
2431
+ CloseButNoCigar();
2432
+ break;
2433
+ }
2434
+ case 42:
2435
+ DoSomethingSpecial();
2436
+ [[fallthrough]];
2437
+ default:
2438
+ DoSomethingGeneric();
2439
+ break;
2440
+ }
2441
+ ```
2442
+
2443
+ # Inclusive Language
2444
+
2445
+ In all code, including naming and comments, use inclusive language and avoid terms that other programmers might find disrespectful or offensive (such as "master" and "slave", "blacklist" and "whitelist", or "redline"), even if the terms also have an ostensibly neutral meaning. Similarly, use gender-neutral language unless you're referring to a specific person (and using their pronouns). For example, use "they"/"them"/"their" for people of unspecified gender ([even when singular](https://apastyle.apa.org/style-grammar-guidelines/grammar/singular-they)), and "it"/"its" for software, computers, and other things that aren't people.
2446
+
2447
+ # Naming
2448
+
2449
+ The most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is: a type, a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules.
2450
+
2451
+ Style rules about naming are pretty arbitrary, but we feel that consistency is more important than individual preferences in this area, so regardless of whether you find them sensible or not, the rules are the rules.
2452
+
2453
+ For the purposes of the naming rules below, a "word" is anything that you would write in English without internal spaces. Either words are all lowercase, with underscores between words ("[snake_case](https://en.wikipedia.org/wiki/Snake_case)"), or words are mixed case with the first letter of each word capitalized ("[camelCase](https://en.wikipedia.org/wiki/Camel_case)" or "[PascalCase](https://en.wiktionary.org/wiki/Pascal_case)").
2454
+
2455
+ ## Choosing Names
2456
+
2457
+ Give things names that make their purpose or intent understandable to a new reader, even someone on a different team than the owners. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader.
2458
+
2459
+ Consider the context in which the name will be used. A name should be descriptive even if it is used far from the code that makes it available for use. However, a name should not distract the reader by repeating information that's present in the immediate context. Generally, this means that descriptiveness should be proportional to the name's scope of visibility. A free function declared in a header should probably mention the header's library, while a local variable probably shouldn't explain what function it's within.
2460
+
2461
+ Minimize the use of abbreviations that would likely be unknown to someone outside your project (especially acronyms and initialisms). Do not abbreviate by deleting letters within a word. When an abbreviation is used, prefer to capitalize it as a single "word", e.g., `StartRpc()` rather than `StartRPC()`. As a rule of thumb, an abbreviation is probably OK if it's listed in Wikipedia. Note that certain universally-known abbreviations are OK, such as `i` for a loop index and `T` for a template parameter.
2462
+
2463
+ The names you see most frequently are not like most names; a small number of "vocabulary" names are reused so widely that they are always in context. These names tend to be short or even abbreviated and their full meaning comes from explicit long-form documentation rather than from just comments on their definition and the words within the names. For example, `absl::Status` has a dedicated [page in a devguide](https://abseil.io/docs/cpp/guides/status), documenting its proper use. You probably won't define new vocabulary names very often, but if you do, get additional design review to make sure the chosen names work well when used widely.
2464
+ ```
2465
+ class MyClass {
2466
+ public:
2467
+ int CountFooErrors(const std::vector<Foo>& foos) {
2468
+ int n = 0; // Clear meaning given limited scope and context
2469
+ for (const auto& foo : foos) {
2470
+ ...
2471
+ ++n;
2472
+ }
2473
+ return n;
2474
+ }
2475
+ // Function comment doesn't need to explain that this returns non-OK on
2476
+ // failure as that is implied by the `absl::Status` return type, but it
2477
+ // might document behavior for some specific codes.
2478
+ absl::Status DoSomethingImportant() {
2479
+ std::string fqdn = ...; // Well-known abbreviation for Fully Qualified Domain Name
2480
+ return absl::OkStatus();
2481
+ }
2482
+ private:
2483
+ const int kMaxAllowedConnections = ...; // Clear meaning within context
2484
+ };
2485
+ ```
2486
+
2487
+ ```
2488
+ class MyClass {
2489
+ public:
2490
+ int CountFooErrors(const std::vector<Foo>& foos) {
2491
+ int total_number_of_foo_errors = 0; // Overly verbose given limited scope and context
2492
+ for (int foo_index = 0; foo_index < foos.size(); ++foo_index) { // Use idiomatic `i`
2493
+ ...
2494
+ ++total_number_of_foo_errors;
2495
+ }
2496
+ return total_number_of_foo_errors;
2497
+ }
2498
+ // A return type with a generic name is unclear without widespread education.
2499
+ Result DoSomethingImportant() {
2500
+ int cstmr_id = ...; // Deletes internal letters
2501
+ }
2502
+ private:
2503
+ const int kNum = ...; // Unclear meaning within broad scope
2504
+ };
2505
+ ```
2506
+
2507
+ ## File Names
2508
+
2509
+ Filenames should be all lowercase and can include underscores (`_`) or dashes (`-`). Follow the convention that your project uses. If there is no consistent local pattern to follow, prefer "`_`".
2510
+
2511
+ Examples of acceptable file names:
2512
+
2513
+ * `my_useful_class.cc`
2514
+ * `my-useful-class.cc`
2515
+ * `myusefulclass.cc`
2516
+ * `myusefulclass_test.cc // _unittest and _regtest are deprecated.`
2517
+
2518
+ C++ files should have a `.cc` filename extension, and header files should have a `.h` extension. Files that rely on being textually included at specific points should end in `.inc` (see also the section on [self-contained headers](#Self_contained_Headers)).
2519
+
2520
+ Do not use filenames that already exist in `/usr/include`, such as `db.h`.
2521
+
2522
+ In general, make your filenames very specific. For example, use `http_server_logs.h` rather than `logs.h`. A very common case is to have a pair of files called, e.g., `foo_bar.h` and `foo_bar.cc`, defining a class called `FooBar`.
2523
+
2524
+ ## Type Names
2525
+
2526
+ Type names start with a capital letter and have a capital letter for each new word, with no underscores: `MyExcitingClass`, `MyExcitingEnum`.
2527
+
2528
+ The names of all types — classes, structs, type aliases, enums, and type template parameters — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example:
2529
+ ```
2530
+ // classes and structs
2531
+ class UrlTable { ...
2532
+ class UrlTableTester { ...
2533
+ struct UrlTableProperties { ...
2534
+
2535
+ // typedefs
2536
+ typedef hash_map<UrlTableProperties*, std::string> PropertiesMap;
2537
+
2538
+ // using aliases
2539
+ using PropertiesMap = hash_map<UrlTableProperties*, std::string>;
2540
+
2541
+ // enums
2542
+ enum class UrlTableError { ...
2543
+ ```
2544
+
2545
+ ## Concept Names
2546
+
2547
+ Concept names follow the same rules as [type names](#Type_Names).
2548
+
2549
+ ## Variable Names
2550
+
2551
+ The names of variables (including function parameters) and data members are `snake_case` (all lowercase, with underscores between words). Data members of classes (but not structs) additionally have trailing underscores. For instance: `a_local_variable`, `a_struct_data_member`, `a_class_data_member_`.
2552
+
2553
+ **COMMON VARIABLE NAMES**
2554
+
2555
+ For example:
2556
+ ```
2557
+ std::string table_name; // OK - snake_case.
2558
+ ```
2559
+
2560
+ ```
2561
+ std::string tableName; // Bad - mixed case.
2562
+ ```
2563
+
2564
+ **CLASS DATA MEMBERS**
2565
+
2566
+ Data members of classes, both static and non-static, are named like ordinary nonmember variables, but with a trailing underscore. The exception to this is static constant class members, which should follow the rules for [naming constants](#Constant_Names).
2567
+ ```
2568
+ class TableInfo {
2569
+ public:
2570
+ ...
2571
+ static const int kTableVersion = 3; // OK - constant naming.
2572
+ ...
2573
+
2574
+ private:
2575
+ std::string table_name_; // OK - underscore at end.
2576
+ static Pool<TableInfo>* pool_; // OK.
2577
+ };
2578
+ ```
2579
+
2580
+ **STRUCT DATA MEMBERS**
2581
+
2582
+ Data members of structs, both static and non-static, are named like ordinary nonmember variables. They do not have the trailing underscores that data members in classes have.
2583
+ ```
2584
+ struct UrlTableProperties {
2585
+ std::string name;
2586
+ int num_entries;
2587
+ static Pool<UrlTableProperties>* pool;
2588
+ };
2589
+ ```
2590
+
2591
+ See [Structs vs. Classes](#Structs_vs._Classes) for a discussion of when to use a struct versus a class.
2592
+
2593
+ ## Constant Names
2594
+
2595
+ Variables declared `constexpr` or `const`, and whose value is fixed for the duration of the program, are named with a leading "k" followed by mixed case. Underscores can be used as separators in the rare cases where capitalization cannot be used for separation. For example:
2596
+ ```
2597
+ const int kDaysInAWeek = 7;
2598
+ const int kAndroid8_0_0 = 24; // Android 8.0.0
2599
+ ```
2600
+
2601
+ All such variables with static storage duration (i.e., statics and globals, see [Storage Duration](http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration) for details) should be named this way, including those that are static constant class data members and those in templates where different instantiations of the template may have different values. This convention is optional for variables of other storage classes, e.g., automatic variables; otherwise the usual variable naming rules apply. For example:
2602
+ ```
2603
+ void ComputeFoo(absl::string_view suffix) {
2604
+ // Either of these is acceptable.
2605
+ const absl::string_view kPrefix = "prefix";
2606
+ const absl::string_view prefix = "prefix";
2607
+ ...
2608
+ }
2609
+ ```
2610
+
2611
+ ```
2612
+ void ComputeFoo(absl::string_view suffix) {
2613
+ // Bad - different invocations of ComputeFoo give kCombined different values.
2614
+ const std::string kCombined = absl::StrCat(kPrefix, suffix);
2615
+ ...
2616
+ }
2617
+ ```
2618
+
2619
+ ## Function Names
2620
+
2621
+ Ordinarily, functions follow [PascalCase](https://en.wiktionary.org/wiki/Pascal_case): start with a capital letter and have a capital letter for each new word.
2622
+ ```
2623
+ AddTableEntry()
2624
+ DeleteUrl()
2625
+ OpenFileOrDie()
2626
+ ```
2627
+
2628
+ The same naming rule applies to class- and namespace-scope constants that are exposed as part of an API and that are intended to look like functions, because the fact that they're objects rather than functions is an unimportant implementation detail.
2629
+
2630
+ Accessors and mutators (get and set functions) may be named like variables, in `snake_case`. These often correspond to actual member variables, but this is not required. For example, `int count()` and `void set_count(int count)`.
2631
+
2632
+ ## Namespace Names
2633
+
2634
+ Namespace names are `snake_case` (all lowercase, with underscores between words).
2635
+
2636
+ When [choosing names](#General_Naming_Rules) for namespaces, note that names must be fully qualified when used in a header outside the namespace, because [unqualified Aliases are generally banned](#Aliases).
2637
+
2638
+ Top-level namespaces must be globally unique and recognizable, so each one should be owned by a single project or team, with a name based on the name of that project or team. Usually, all code in the namespace should be under one or more directories with the same name as the namespace.
2639
+
2640
+ Nested namespaces should avoid the names of well-known top-level namespaces, especially `std` and `absl`, because in C++, nested namespaces do not protect from collisions with names in other namespaces (see [TotW #130](https://abseil.io/tips/130)).
2641
+
2642
+ ## Enumerator Names
2643
+
2644
+ Enumerators (for both scoped and unscoped enums) should be named like [constants](#Constant_Names), not like [macros](#Macro_Names). That is, use `kEnumName` not `ENUM_NAME`.
2645
+ ```
2646
+ enum class UrlTableError {
2647
+ kOk = 0,
2648
+ kOutOfMemory,
2649
+ kMalformedInput,
2650
+ };
2651
+ ```
2652
+
2653
+ ```
2654
+ enum class AlternateUrlTableError {
2655
+ OK = 0,
2656
+ OUT_OF_MEMORY = 1,
2657
+ MALFORMED_INPUT = 2,
2658
+ };
2659
+ ```
2660
+
2661
+ Until January 2009, the style was to name enum values like [macros](#Macro_Names). This caused problems with name collisions between enum values and macros. Hence, the change to prefer constant-style naming was put in place. New code should use constant-style naming.
2662
+
2663
+ ## Template Parameter Names
2664
+
2665
+ Template parameters should follow the naming style for their category: type template parameters should follow the rules for naming [types](#Type_Names), and non-type template parameters should follow the rules for naming [variables](#Variable_Names) or [constants](#Constant_Names).
2666
+
2667
+ ## Macro Names
2668
+
2669
+ You're not really going to [define a macro](#Preprocessor_Macros), are you? If you do, they're like this: `MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE`.
2670
+
2671
+ Please see the [description of macros](#Preprocessor_Macros); in general macros should *not* be used. However, if they are absolutely needed, then they should be named with all capitals and underscores, and with a project-specific prefix.
2672
+ ```
2673
+ #define MYPROJECT_ROUND(x) ...
2674
+ ```
2675
+
2676
+ ## Aliases
2677
+
2678
+ The name for an [alias](#Aliases) follows the same principles as any other new name, applied in the context where the alias is defined rather than where the original name appears.
2679
+
2680
+ ## Exceptions to Naming Rules
2681
+
2682
+ If you are naming something that is analogous to an existing C or C++ entity (or a Rust entity via interop), then you can follow the existing naming convention scheme.
2683
+
2684
+ `bigopen()` : function name, follows form of `open()`
2685
+
2686
+ `uint` : `typedef`
2687
+
2688
+ `bigpos` : `struct` or `class`, follows form of `pos`
2689
+
2690
+ `sparse_hash_map` : STL-like entity; follows STL naming conventions
2691
+
2692
+ `LONGLONG_MAX` : a constant, as in `INT_MAX`
2693
+
2694
+ # Comments
2695
+
2696
+ Comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments.
2697
+
2698
+ When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you!
2699
+
2700
+ ## Comment Style
2701
+
2702
+ Use either the `//` or `/* */` syntax, as long as you are consistent.
2703
+
2704
+ While either syntax is acceptable, `//` is *much* more common. Be consistent with how you comment and what style you use where.
2705
+
2706
+ ## File Comments
2707
+
2708
+ Start each file with license boilerplate.
2709
+
2710
+ If a source file (such as a `.h` file) declares multiple user-facing abstractions (common functions, related classes, etc.), include a comment describing the collection of those abstractions. Include enough detail for future authors to know what does not fit there. However, the detailed documentation about individual abstractions belongs with those abstractions, not at the file level.
2711
+
2712
+ For instance, if you write a file comment for `frobber.h`, you do not need to include a file comment in `frobber.cc` or `frobber_test.cc`. On the other hand, if you write a collection of classes in `registered_objects.cc` that has no associated header file, you must include a file comment in `registered_objects.cc`.
2713
+
2714
+ **LEGAL NOTICE AND AUTHOR LINE**
2715
+
2716
+ Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL).
2717
+
2718
+ If you make significant changes to a file with an author line, consider deleting the author line. New files should usually not contain copyright notice or author line.
2719
+
2720
+ ## Struct and Class Comments
2721
+
2722
+ Every non-obvious class or struct declaration should have an accompanying comment that describes what it is for and how it should be used.
2723
+ ```
2724
+ // Iterates over the contents of a GargantuanTable.
2725
+ // Example:
2726
+ // std::unique_ptr<GargantuanTableIterator> iter = table->NewIterator();
2727
+ // for (iter->Seek("foo"); !iter->done(); iter->Next()) {
2728
+ // process(iter->key(), iter->value());
2729
+ // }
2730
+ class GargantuanTableIterator {
2731
+ ...
2732
+ };
2733
+ ```
2734
+
2735
+ **CLASS COMMENTS**
2736
+
2737
+ The class comment should provide the reader with enough information to know how and when to use the class, as well as any additional considerations necessary to correctly use the class. Document the synchronization assumptions the class makes, if any. If an instance of the class can be accessed by multiple threads, take extra care to document the rules and invariants surrounding multithreaded use.
2738
+
2739
+ The class comment is often a good place for a small example code snippet demonstrating a simple and focused usage of the class.
2740
+
2741
+ When sufficiently separated (e.g., `.h` and `.cc` files), comments describing the use of the class should go together with its interface definition; comments about the class operation and implementation should accompany the implementation of the class's methods.
2742
+
2743
+ ## Function Comments
2744
+
2745
+ Declaration comments describe use of the function (when it is non-obvious); comments at the definition of a function describe operation.
2746
+
2747
+ **FUNCTION DECLARATIONS**
2748
+
2749
+ Almost every function declaration should have comments immediately preceding it that describe what the function does and how to use it. These comments may be omitted only if the function is simple and obvious (e.g., simple accessors for obvious properties of the class). Private methods and functions declared in `.cc` files are not exempt. Function comments should be written with an implied subject of *This function* and should start with the verb phrase; for example, "Opens the file", rather than "Open the file". In general, these comments do not describe how the function performs its task. Instead, that should be left to comments in the function definition.
2750
+
2751
+ Types of things to mention in comments at the function declaration:
2752
+
2753
+ * What the inputs and outputs are. If function argument names
2754
+ are provided in `backticks`, then code-indexing
2755
+ tools may be able to present the documentation better.
2756
+ * For class member functions: whether the object remembers
2757
+ reference or pointer arguments beyond the duration of the method
2758
+ call. This is quite common for pointer/reference arguments to
2759
+ constructors.
2760
+ * For each pointer argument, whether it is allowed to be null and what happens
2761
+ if it is.
2762
+ * For each output or input/output argument, what happens to any state that argument
2763
+ is in (e.g., is the state appended to or overwritten?).
2764
+ * If there are any performance implications of how a
2765
+ function is used.
2766
+
2767
+ Here is an example:
2768
+ ```
2769
+ // Returns an iterator for this table, positioned at the first entry
2770
+ // lexically greater than or equal to `start_word`. If there is no
2771
+ // such entry, returns a null pointer. The client must not use the
2772
+ // iterator after the underlying GargantuanTable has been destroyed.
2773
+ //
2774
+ // This method is equivalent to:
2775
+ // std::unique_ptr<Iterator> iter = table->NewIterator();
2776
+ // iter->Seek(start_word);
2777
+ // return iter;
2778
+ std::unique_ptr<Iterator> GetIterator(absl::string_view start_word) const;
2779
+ ```
2780
+
2781
+ However, do not be unnecessarily verbose or state the completely obvious.
2782
+
2783
+ When documenting function overrides, focus on the specifics of the override itself, rather than repeating the comment from the overridden function. In many of these cases, the override needs no additional documentation and thus no comment is required.
2784
+
2785
+ When commenting constructors and destructors, remember that the person reading your code knows what constructors and destructors are for, so comments that just say something like "destroys this object" are not useful. Document what constructors do with their arguments (for example, if they take ownership of pointers), and what cleanup the destructor does. If this is trivial, just skip the comment. It is quite common for destructors not to have a header comment.
2786
+
2787
+ **FUNCTION DEFINITIONS**
2788
+
2789
+ If there is anything tricky about how a function does its job, the function definition should have an explanatory comment. For example, in the definition comment you might describe any coding tricks you use, give an overview of the steps you go through, or explain why you chose to implement the function in the way you did rather than using a viable alternative. For instance, you might mention why it must acquire a lock for the first half of the function but why it is not needed for the second half.
2790
+
2791
+ Note you should *not* just repeat the comments given with the function declaration, in the `.h` file or wherever. It's okay to recapitulate briefly what the function does, but the focus of the comments should be on how it does it.
2792
+
2793
+ ## Variable Comments
2794
+
2795
+ In general the actual name of the variable should be descriptive enough to give a good idea of what the variable is used for. In certain cases, more comments are required.
2796
+
2797
+ **CLASS DATA MEMBERS**
2798
+
2799
+ The purpose of each class data member (also called an instance variable or member variable) must be clear. If there are any invariants (special values, relationships between members, lifetime requirements) not clearly expressed by the type and name, they must be commented. However, if the type and name suffice (`int num_events\_;`), no comment is needed.
2800
+
2801
+ In particular, add comments to describe the existence and meaning of sentinel values, such as nullptr or -1, when they are not obvious. For example:
2802
+ ```
2803
+ private:
2804
+ // Used to bounds-check table accesses. -1 means
2805
+ // that we don't yet know how many entries the table has.
2806
+ int num_total_entries_;
2807
+ ```
2808
+
2809
+ **GLOBAL VARIABLES**
2810
+
2811
+ All global variables should have a comment describing what they are, what they are used for, and (if unclear) why they need to be global. For example:
2812
+ ```
2813
+ // The total number of test cases that we run through in this regression test.
2814
+ const int kNumTestCases = 6;
2815
+ ```
2816
+
2817
+ ## Implementation Comments
2818
+
2819
+ In your implementation you should have comments in tricky, non-obvious, interesting, or important parts of your code.
2820
+
2821
+ **EXPLANATORY COMMENTS**
2822
+
2823
+ Tricky or complicated code blocks should have comments before them.
2824
+
2825
+ **FUNCTION ARGUMENT COMMENTS**
2826
+
2827
+ When the meaning of a function argument is nonobvious, consider one of the following remedies:
2828
+
2829
+ * If the argument is a literal constant, and the same constant is
2830
+ used in multiple function calls in a way that tacitly assumes they're
2831
+ the same, you should use a named constant to make that constraint
2832
+ explicit, and to guarantee that it holds.
2833
+ * Consider changing the function signature to replace a `bool`
2834
+ argument with an `enum` argument. This will make the argument
2835
+ values self-describing.
2836
+ * For functions that have several configuration options, consider
2837
+ defining a single class or struct to hold all the options
2838
+ ,
2839
+ and pass an instance of that.
2840
+ This approach has several advantages. Options are referenced by name
2841
+ at the call site, which clarifies their meaning. It also reduces
2842
+ function argument count, which makes function calls easier to read and
2843
+ write. As an added benefit, you don't have to change call sites when
2844
+ you add another option.
2845
+ * Replace large or complex nested expressions with named variables.
2846
+ * As a last resort, use comments to clarify argument meanings at the
2847
+ call site.
2848
+
2849
+ Consider the following example:
2850
+ ```
2851
+ // What are these arguments?
2852
+ const DecimalNumber product = CalculateProduct(values, 7, false, nullptr);
2853
+ ```
2854
+
2855
+ versus:
2856
+ ```
2857
+ ProductOptions options;
2858
+ options.set_precision_decimals(7);
2859
+ options.set_use_cache(ProductOptions::kDontUseCache);
2860
+ const DecimalNumber product =
2861
+ CalculateProduct(values, options, /*completion_callback=*/nullptr);
2862
+ ```
2863
+
2864
+ **DON'TS**
2865
+
2866
+ Do not state the obvious. In particular, don't literally describe what code does, unless the behavior is nonobvious to a reader who understands C++ well. Instead, provide higher-level comments that describe *why* the code does what it does, or make the code self-describing.
2867
+
2868
+ Compare this:
2869
+ ```
2870
+ // Find the element in the vector. <-- Bad: obvious!
2871
+ if (std::find(v.begin(), v.end(), element) != v.end()) {
2872
+ Process(element);
2873
+ }
2874
+ ```
2875
+
2876
+ To this:
2877
+ ```
2878
+ // Process "element" unless it was already processed.
2879
+ if (std::find(v.begin(), v.end(), element) != v.end()) {
2880
+ Process(element);
2881
+ }
2882
+ ```
2883
+
2884
+ Self-describing code doesn't need a comment. The comment from the example above would be obvious:
2885
+ ```
2886
+ if (!IsAlreadyProcessed(element)) {
2887
+ Process(element);
2888
+ }
2889
+ ```
2890
+
2891
+ ## Punctuation, Spelling, and Grammar
2892
+
2893
+ Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones.
2894
+
2895
+ Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style.
2896
+
2897
+ Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal.
2898
+
2899
+ ## TODO Comments
2900
+
2901
+ Use `TODO` comments for code that is temporary, a short-term solution, or good-enough but not perfect.
2902
+
2903
+ `TODO`s should include the string `TODO` in all caps, followed by the bug ID, name, e-mail address, or other identifier of the person or issue with the best context about the problem referenced by the `TODO`.
2904
+
2905
+ Recommended styles are (in order of preference):
2906
+ ```
2907
+ // TODO: bug 12345678 - Remove this after the 2047q4 compatibility window expires.
2908
+ // TODO: example.com/my-design-doc - Manually fix up this code the next time it's touched.
2909
+ // TODO(bug 12345678): Update this list after the Foo service is turned down.
2910
+ // TODO(John): Use a "\*" here for concatenation operator.
2911
+ ```
2912
+
2913
+ If your `TODO` is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code when all clients can handle XML responses.").
2914
+
2915
+ # Formatting
2916
+
2917
+ Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone's code easily.
2918
+
2919
+ To help you format code correctly, we've created a [settings file for emacs](https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el).
2920
+
2921
+ ## Line Length
2922
+
2923
+ Each line of text in your code should be at most 80 characters long.
2924
+
2925
+ We recognize that this rule is controversial, but so much existing code already adheres to it, and we feel that consistency is important.
2926
+
2927
+ Those who favor this rule argue that it is rude to force them to resize their windows and there is no need for anything longer. Some folks are used to having several code windows side-by-side, and thus don't have room to widen their windows in any case. People set up their work environment assuming a particular maximum window width, and 80 columns has been the traditional standard. Why change it?
2928
+
2929
+ Proponents of change argue that a wider line can make code more readable. The 80-column limit is an hidebound throwback to 1960s mainframes; modern equipment has wide screens that can easily show longer lines.
2930
+
2931
+ 80 characters is the maximum.
2932
+
2933
+ A line may exceed 80 characters if it is
2934
+
2935
+ * a comment line which is not feasible to split without harming
2936
+ readability, ease of cut and paste or auto-linking -- e.g., if a line
2937
+ contains an example command or a literal URL longer than 80 characters.
2938
+ * a string literal that cannot easily be wrapped at 80 columns.
2939
+ This may be because it contains URIs or other semantically-critical pieces,
2940
+ or because the literal contains an embedded language, or because it is a
2941
+ multiline literal whose newlines are significant, such as help messages.
2942
+ In these cases, breaking up the literal would
2943
+ reduce readability, searchability, ability to click links, etc. Except for
2944
+ test code, such literals should appear at namespace scope near the top of a
2945
+ file. If a tool like Clang-Format doesn't recognize the unsplittable content,
2946
+ [disable the tool](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code) around the content as necessary.
2947
+
2948
+ (We must balance between usability/searchability of such literals and the readability of the code around them.)
2949
+
2950
+ - an include statement.
2951
+ - a [header guard.](#The__define_Guard)
2952
+ - a using-declaration.
2953
+
2954
+ ## Non-ASCII Characters
2955
+
2956
+ Non-ASCII characters should be rare, and must use UTF-8 formatting.
2957
+
2958
+ You shouldn't hard-code user-facing text in source, even English, so use of non-ASCII characters should be rare. However, in certain cases it is appropriate to include such words in your code. For example, if your code parses data files from foreign sources, it may be appropriate to hard-code the non-ASCII string(s) used in those data files as delimiters. More commonly, unit test code (which does not need to be localized) might contain non-ASCII strings. In such cases, you should use UTF-8, since that is an encoding understood by most tools able to handle more than just ASCII.
2959
+
2960
+ Hex encoding is also OK, and encouraged where it enhances readability — for example, `"\xEF\xBB\xBF"`, or, even more simply, `"\uFEFF"`, is the Unicode zero-width no-break space character, which would be invisible if included in the source as straight UTF-8.
2961
+
2962
+ When possible, avoid the `u8` prefix. It has significantly different semantics starting in C++20 than in C++17, producing arrays of `char8_t` rather than `char`, and will change again in C++23.
2963
+
2964
+ You shouldn't use `char16_t` and `char32_t` character types, since they're for non-UTF-8 text. For similar reasons you also shouldn't use `wchar_t` (unless you're writing code that interacts with the Windows API, which uses `wchar_t` extensively).
2965
+
2966
+ ## Spaces vs. Tabs
2967
+
2968
+ Use only spaces, and indent 2 spaces at a time.
2969
+
2970
+ We use spaces for indentation. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key.
2971
+
2972
+ ## Function Declarations and Definitions
2973
+
2974
+ Return type on the same line as function name, parameters on the same line if they fit. Wrap parameter lists which do not fit on a single line as you would wrap arguments in a [function call](#Function_Calls).
2975
+
2976
+ Functions look like this:
2977
+ ```
2978
+ ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
2979
+ DoSomething();
2980
+ ...
2981
+ }
2982
+ ```
2983
+
2984
+ If you have too much text to fit on one line:
2985
+ ```
2986
+ ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
2987
+ Type par_name3) {
2988
+ DoSomething();
2989
+ ...
2990
+ }
2991
+ ```
2992
+
2993
+ or if you cannot fit even the first parameter:
2994
+ ```
2995
+ ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
2996
+ Type par_name1, // 4 space indent
2997
+ Type par_name2,
2998
+ Type par_name3) {
2999
+ DoSomething(); // 2 space indent
3000
+ ...
3001
+ }
3002
+ ```
3003
+
3004
+ Some points to note:
3005
+
3006
+ * Choose good parameter names.
3007
+ * A parameter name may be omitted only if the parameter is not used in the
3008
+ function's definition.
3009
+ * If you cannot fit the return type and the function
3010
+ name on a single line, break between them.
3011
+ * If you break after the return type of a function
3012
+ declaration or definition, do not indent.
3013
+ * The open parenthesis is always on the same line as
3014
+ the function name.
3015
+ * There is never a space between the function name
3016
+ and the open parenthesis.
3017
+ * There is never a space between the parentheses and
3018
+ the parameters.
3019
+ * The open curly brace is always on the end of the last line of the function
3020
+ declaration, not the start of the next line.
3021
+ * The close curly brace is either on the last line by
3022
+ itself or on the same line as the open curly brace.
3023
+ * There should be a space between the close
3024
+ parenthesis and the open curly brace.
3025
+ * All parameters should be aligned if possible.
3026
+ * Default indentation is 2 spaces.
3027
+ * Wrapped parameters have a 4 space indent.
3028
+
3029
+ Unused parameters that are obvious from context may omit the name:
3030
+ ```
3031
+ class Foo {
3032
+ public:
3033
+ Foo(const Foo&) = delete;
3034
+ Foo& operator=(const Foo&) = delete;
3035
+ };
3036
+ ```
3037
+
3038
+ Unused parameters that might not be obvious should comment out the variable name in the function definition:
3039
+ ```
3040
+ class Shape {
3041
+ public:
3042
+ virtual void Rotate(double radians) = 0;
3043
+ };
3044
+
3045
+ class Circle : public Shape {
3046
+ public:
3047
+ void Rotate(double radians) override;
3048
+ };
3049
+
3050
+ void Circle::Rotate(double /*radians*/) {}
3051
+ ```
3052
+
3053
+ ```
3054
+ // Bad - if someone wants to implement later, it's not clear what the
3055
+ // variable means.
3056
+ void Circle::Rotate(double) {}
3057
+ ```
3058
+
3059
+ Attributes, and macros that expand to attributes, appear at the very beginning of the function declaration or definition, before the return type:
3060
+ ```
3061
+ ABSL_ATTRIBUTE_NOINLINE void ExpensiveFunction();
3062
+ [[nodiscard]] bool IsOk();
3063
+ ```
3064
+
3065
+ ## Lambda Expressions
3066
+
3067
+ Format parameters and bodies as for any other function, and capture lists like other comma-separated lists.
3068
+
3069
+ For by-reference captures, do not leave a space between the ampersand (`&`) and the variable name.
3070
+ ```
3071
+ int x = 0;
3072
+ auto x_plus_n = MISSING_LINK -> int { return x + n; }
3073
+ ```
3074
+
3075
+ Short lambdas may be written inline as function arguments.
3076
+ ```
3077
+ absl::flat_hash_set<int> to_remove = {7, 8, 9};
3078
+ std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
3079
+ digits.erase(std::remove_if(digits.begin(), digits.end(), MISSING_LINK {
3080
+ return to_remove.contains(i);
3081
+ }),
3082
+ digits.end());
3083
+ ```
3084
+
3085
+ ## Floating-point Literals
3086
+
3087
+ Floating-point literals should always have a radix point, with digits on both sides, even if they use exponential notation. Readability is improved if all floating-point literals take this familiar form, as this helps ensure that they are not mistaken for integer literals, and that the `E`/`e` of the exponential notation is not mistaken for a hexadecimal digit. It is fine to initialize a floating-point variable with an integer literal (assuming the variable type can exactly represent that integer), but note that a number in exponential notation is never an integer literal.
3088
+ ```
3089
+ float f = 1.f;
3090
+ long double ld = -.5L;
3091
+ double d = 1248e6;
3092
+ ```
3093
+
3094
+ ```
3095
+ float f = 1.0f;
3096
+ float f2 = 1.0; // Also OK
3097
+ float f3 = 1; // Also OK
3098
+ long double ld = -0.5L;
3099
+ double d = 1248.0e6;
3100
+ ```
3101
+
3102
+ ## Function Calls
3103
+
3104
+ Either write the call all on a single line, wrap the arguments at the parenthesis, or start the arguments on a new line indented by four spaces and continue at that 4 space indent. In the absence of other considerations, use the minimum number of lines, including placing multiple arguments on each line where appropriate.
3105
+
3106
+ Function calls have the following format:
3107
+ ```
3108
+ bool result = DoSomething(argument1, argument2, argument3);
3109
+ ```
3110
+
3111
+ If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do not add spaces after the open paren or before the close paren:
3112
+ ```
3113
+ bool result = DoSomething(averyveryveryverylongargument1,
3114
+ argument2, argument3);
3115
+ ```
3116
+
3117
+ Arguments may optionally all be placed on subsequent lines with a four space indent:
3118
+ ```
3119
+ if (...) {
3120
+ ...
3121
+ ...
3122
+ if (...) {
3123
+ bool result = DoSomething(
3124
+ argument1, argument2, // 4 space indent
3125
+ argument3, argument4);
3126
+ ...
3127
+ }
3128
+ ```
3129
+
3130
+ Put multiple arguments on a single line to reduce the number of lines necessary for calling a function unless there is a specific readability problem. Some find that formatting with strictly one argument on each line is more readable and simplifies editing of the arguments. However, we prioritize for the reader over the ease of editing arguments, and most readability problems are better addressed with the following techniques.
3131
+
3132
+ If having multiple arguments in a single line decreases readability due to the complexity or confusing nature of the expressions that make up some arguments, try creating variables that capture those arguments in a descriptive name:
3133
+ ```
3134
+ int my_heuristic = scores[x] * y + bases[x];
3135
+ bool result = DoSomething(my_heuristic, x, y, z);
3136
+ ```
3137
+
3138
+ Or put the confusing argument on its own line with an explanatory comment:
3139
+ ```
3140
+ bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic.
3141
+ x, y, z);
3142
+ ```
3143
+
3144
+ If there is still a case where one argument is significantly more readable on its own line, then put it on its own line. The decision should be specific to the argument which is made more readable rather than a general policy.
3145
+
3146
+ Sometimes arguments form a structure that is important for readability. In those cases, feel free to format the arguments according to that structure:
3147
+ ```
3148
+ // Transform the widget by a 3x3 matrix.
3149
+ my_widget.Transform(x1, x2, x3,
3150
+ y1, y2, y3,
3151
+ z1, z2, z3);
3152
+ ```
3153
+
3154
+ ## Braced Initializer List Format
3155
+
3156
+ Format a braced initializer list exactly like you would format a function call in its place.
3157
+
3158
+ If the braced list follows a name (e.g., a type or variable name), format as if the `{}` were the parentheses of a function call with that name. If there is no name, assume a zero-length name.
3159
+ ```
3160
+ // Examples of braced init list on a single line.
3161
+ return {foo, bar};
3162
+ functioncall({foo, bar});
3163
+ std::pair<int, int> p{foo, bar};
3164
+
3165
+ // When you have to wrap.
3166
+ SomeFunction(
3167
+ {"assume a zero-length name before {"},
3168
+ some_other_function_parameter);
3169
+ SomeType variable{
3170
+ some, other, values,
3171
+ {"assume a zero-length name before {"},
3172
+ SomeOtherType{
3173
+ "Very long string requiring the surrounding breaks.",
3174
+ some, other, values},
3175
+ SomeOtherType{"Slightly shorter string",
3176
+ some, other, values}};
3177
+ SomeType variable{
3178
+ "This is too long to fit all in one line"};
3179
+ MyType m = { // Here, you could also break before {.
3180
+ superlongvariablename1,
3181
+ superlongvariablename2,
3182
+ {short, interior, list},
3183
+ {interiorwrappinglist,
3184
+ interiorwrappinglist2}};
3185
+ ```
3186
+
3187
+ ## Looping and branching statements
3188
+
3189
+ At a high level, looping or branching statements consist of the following **components**:
3190
+
3191
+ * One or more **statement keywords** (e.g., `if`,
3192
+ `else`, `switch`, `while`, `do`,
3193
+ or `for`).
3194
+ * One **condition or iteration specifier**, inside
3195
+ parentheses.
3196
+ * One or more **controlled statements**, or blocks of
3197
+ controlled statements.
3198
+
3199
+ For these statements:
3200
+
3201
+ * The components of the statement should be separated by single spaces (not
3202
+ line breaks).
3203
+ * Inside the condition or iteration specifier, put one space (or a line
3204
+ break) between each semicolon and the next token, except if the token is a
3205
+ closing parenthesis or another semicolon.
3206
+ * Inside the condition or iteration specifier, do not put a space after the
3207
+ opening parenthesis or before the closing parenthesis.
3208
+ * Put any controlled statements inside blocks (i.e., use curly braces).
3209
+ * Inside the controlled blocks, put one line break immediately after the
3210
+ opening brace, and one line break immediately before the closing brace.
3211
+ ```
3212
+ if (condition) { // Good - no spaces inside parentheses, space before brace.
3213
+ DoOneThing(); // Good - two-space indent.
3214
+ DoAnotherThing();
3215
+ } else if (int a = f(); a != 3) { // Good - closing brace on new line, else on same line.
3216
+ DoAThirdThing(a);
3217
+ } else {
3218
+ DoNothing();
3219
+ }
3220
+
3221
+ // Good - the same rules apply to loops.
3222
+ while (condition) {
3223
+ RepeatAThing();
3224
+ }
3225
+
3226
+ // Good - the same rules apply to loops.
3227
+ do {
3228
+ RepeatAThing();
3229
+ } while (condition);
3230
+
3231
+ // Good - the same rules apply to loops.
3232
+ for (int i = 0; i < 10; ++i) {
3233
+ RepeatAThing();
3234
+ }
3235
+ ```
3236
+
3237
+ ```
3238
+ if(condition) {} // Bad - space missing after `if`.
3239
+ else if ( condition ) {} // Bad - space between the parentheses and the condition.
3240
+ else if (condition){} // Bad - space missing before `{`.
3241
+ else if(condition){} // Bad - multiple spaces missing.
3242
+
3243
+ for (int a = f();a == 10) {} // Bad - space missing after the semicolon.
3244
+
3245
+ // Bad - `if ... else` statement does not have braces everywhere.
3246
+ if (condition)
3247
+ foo;
3248
+ else {
3249
+ bar;
3250
+ }
3251
+
3252
+ // Bad - `if` statement too long to omit braces.
3253
+ if (condition)
3254
+ // Comment
3255
+ DoSomething();
3256
+
3257
+ // Bad - `if` statement too long to omit braces.
3258
+ if (condition1 &&
3259
+ condition2)
3260
+ DoSomething();
3261
+ ```
3262
+
3263
+ For historical reasons, we allow one exception to the above rules: the curly braces for the controlled statement or the line breaks inside the curly braces may be omitted if as a result the entire statement appears on either a single line (in which case there is a space between the closing parenthesis and the controlled statement) or on two lines (in which case there is a line break after the closing parenthesis and there are no braces).
3264
+ ```
3265
+ // OK - fits on one line.
3266
+ if (x == kFoo) { return new Foo(); }
3267
+
3268
+ // OK - braces are optional in this case.
3269
+ if (x == kFoo) return new Foo();
3270
+
3271
+ // OK - condition fits on one line, body fits on another.
3272
+ if (x == kBar)
3273
+ Bar(arg1, arg2, arg3);
3274
+ ```
3275
+
3276
+ This exception does not apply to multi-keyword statements like `if ... else` or `do ... while`.
3277
+ ```
3278
+ // Bad - `if ... else` statement is missing braces.
3279
+ if (x) DoThis();
3280
+ else DoThat();
3281
+
3282
+ // Bad - `do ... while` statement is missing braces.
3283
+ do DoThis();
3284
+ while (x);
3285
+ ```
3286
+
3287
+ Use this style only when the statement is brief, and consider that loops and branching statements with complex conditions or controlled statements may be more readable with curly braces. Some projects require curly braces always.
3288
+
3289
+ `case` blocks in `switch` statements can have curly braces or not, depending on your preference. If you do include curly braces, they should be placed as shown below.
3290
+ ```
3291
+ switch (var) {
3292
+ case 0: { // 2 space indent
3293
+ Foo(); // 4 space indent
3294
+ break;
3295
+ }
3296
+ default: {
3297
+ Bar();
3298
+ }
3299
+ }
3300
+ ```
3301
+
3302
+ Empty loop bodies should use either an empty pair of braces or `continue` with no braces, rather than a single semicolon.
3303
+ ```
3304
+ while (condition) {} // Good - `{}` indicates no logic.
3305
+ while (condition) {
3306
+ // Comments are okay, too
3307
+ }
3308
+ while (condition) continue; // Good - `continue` indicates no logic.
3309
+ ```
3310
+
3311
+ ```
3312
+ while (condition); // Bad - looks like part of `do-while` loop.
3313
+ ```
3314
+
3315
+ ## Pointer and Reference Expressions and Types
3316
+
3317
+ No spaces around period or arrow. Pointer operators do not have trailing spaces.
3318
+
3319
+ The following are examples of correctly-formatted pointer and reference expressions:
3320
+ ```
3321
+ x = *p;
3322
+ p = &x;
3323
+ x = r.y;
3324
+ x = r->y;
3325
+ ```
3326
+
3327
+ Note that:
3328
+
3329
+ * There are no spaces around the period or arrow when
3330
+ accessing a member.
3331
+ * Pointer operators have no space after the
3332
+ `*` or `&`.
3333
+
3334
+ When referring to a pointer or reference (variable declarations or definitions, arguments, return types, template parameters, etc.), you must not place a space before the asterisk/ampersand. Use a space to separate the type from the declared name (if present).
3335
+ ```
3336
+ // These are fine.
3337
+ char* c;
3338
+ const std::string& str;
3339
+ int* GetPointer();
3340
+ std::vector<char*> // Note no space between '*' and '>'
3341
+ ```
3342
+
3343
+ It is allowed (if unusual) to declare multiple variables in the same declaration, but it is disallowed if any of those have pointer or reference decorations. Such declarations are easily misread.
3344
+ ```
3345
+ // Fine if helpful for readability.
3346
+ int x, y;
3347
+ ```
3348
+
3349
+ ```
3350
+ int x, *y; // Disallowed - no & or * in multiple declaration
3351
+ int *x, *y; // Disallowed - no & or * in multiple declaration
3352
+ int *x; // Disallowed - & or * must be left of the space
3353
+ char * c; // Bad - spaces on both sides of *
3354
+ const std::string & str; // Bad - spaces on both sides of &
3355
+ ```
3356
+
3357
+ ## Boolean Expressions
3358
+
3359
+ When you have a boolean expression that is longer than the [standard line length](#Line_Length), be consistent in how you break up the lines.
3360
+
3361
+ In this example, the logical AND operator is always at the end of the lines:
3362
+ ```
3363
+ if (this_one_thing > this_other_thing &&
3364
+ a_third_thing == a_fourth_thing &&
3365
+ yet_another && last_one) {
3366
+ ...
3367
+ }
3368
+ ```
3369
+
3370
+ Note that when the code wraps in this example, both of the `&&` logical AND operators are at the end of the line. This is more common in Google code, though wrapping all operators at the beginning of the line is also allowed. Feel free to insert extra parentheses judiciously because they can be very helpful in increasing readability when used appropriately, but be careful about overuse. Also note that you should always use the punctuation operators, such as `&&` and `~`, rather than the word operators, such as `and` and `compl`.
3371
+
3372
+ ## Return Values
3373
+
3374
+ Do not needlessly surround the `return` expression with parentheses.
3375
+
3376
+ Use parentheses in `return expr;` only where you would use them in `x = expr;`.
3377
+ ```
3378
+ return result; // No parentheses in the simple case.
3379
+ // Parentheses OK to make a complex expression more readable.
3380
+ return (some_long_condition &&
3381
+ another_condition);
3382
+ ```
3383
+
3384
+ ```
3385
+ return (value); // You wouldn't write var = (value);
3386
+ return(result); // return is not a function!
3387
+ ```
3388
+
3389
+ ## Variable and Array Initialization
3390
+
3391
+ You may choose between `=`, `()`, and `{}`; the following are all correct:
3392
+ ```
3393
+ int x = 3;
3394
+ int x(3);
3395
+ int x{3};
3396
+ std::string name = "Some Name";
3397
+ std::string name("Some Name");
3398
+ std::string name{"Some Name"};
3399
+ ```
3400
+
3401
+ Be careful when using a braced initialization list `{...}` on a type with an `std::initializer_list` constructor. A nonempty *braced-init-list* prefers the `std::initializer_list` constructor whenever possible. Note that empty braces `{}` are special, and will call a default constructor if available. To force the non-`std::initializer_list` constructor, use parentheses instead of braces.
3402
+ ```
3403
+ std::vector<int> v(100, 1); // A vector containing 100 items: All 1s.
3404
+ std::vector<int> v{100, 1}; // A vector containing 2 items: 100 and 1.
3405
+ ```
3406
+
3407
+ Also, the brace form prevents narrowing of integral types. This can prevent some types of programming errors.
3408
+ ```
3409
+ int pi(3.14); // OK -- pi == 3.
3410
+ int pi{3.14}; // Compile error: narrowing conversion.
3411
+ ```
3412
+
3413
+ ## Preprocessor Directives
3414
+
3415
+ The hash mark that starts a preprocessor directive should always be at the beginning of the line.
3416
+
3417
+ Even when preprocessor directives are within the body of indented code, the directives should start at the beginning of the line.
3418
+ ```
3419
+ // Good - directives at beginning of line
3420
+ if (lopsided_score) {
3421
+ #if DISASTER_PENDING // Correct -- Starts at beginning of line
3422
+ DropEverything();
3423
+ # if NOTIFY // OK but not required -- Spaces after #
3424
+ NotifyClient();
3425
+ # endif
3426
+ #endif
3427
+ BackToNormal();
3428
+ }
3429
+ ```
3430
+
3431
+ ```
3432
+ // Bad - indented directives
3433
+ if (lopsided_score) {
3434
+ #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
3435
+ DropEverything();
3436
+ #endif // Wrong! Do not indent "#endif"
3437
+ BackToNormal();
3438
+ }
3439
+ ```
3440
+
3441
+ ## Class Format
3442
+
3443
+ Sections in `public`, `protected`, and `private` order, each indented one space.
3444
+
3445
+ The basic format for a class definition (lacking the comments, see [Class Comments](#Class_Comments) for a discussion of what comments are needed) is:
3446
+ ```
3447
+ class MyClass : public OtherClass {
3448
+ public: // Note the 1 space indent!
3449
+ MyClass(); // Regular 2 space indent.
3450
+ explicit MyClass(int var);
3451
+ ~MyClass() {}
3452
+
3453
+ void SomeFunction();
3454
+ void SomeFunctionThatDoesNothing() {
3455
+ }
3456
+
3457
+ void set_some_var(int var) { some_var_ = var; }
3458
+ int some_var() const { return some_var_; }
3459
+
3460
+ private:
3461
+ bool SomeInternalFunction();
3462
+
3463
+ int some_var_;
3464
+ int some_other_var_;
3465
+ };
3466
+ ```
3467
+
3468
+ Things to note:
3469
+
3470
+ * Any base class name should be on the same line as
3471
+ the subclass name, subject to the 80-column limit.
3472
+ * The `public:`, `protected:`,
3473
+ and `private:` keywords should be indented
3474
+ one space.
3475
+ * Except for the first instance, these keywords
3476
+ should be preceded by a blank line. This rule is
3477
+ optional in small classes.
3478
+ * Do not leave a blank line after these
3479
+ keywords.
3480
+ * The `public` section should be first,
3481
+ followed by the `protected` and finally the
3482
+ `private` section.
3483
+ * See [Declaration
3484
+ Order](#Declaration_Order) for rules on ordering declarations within
3485
+ each of these sections.
3486
+
3487
+ ## Constructor Initializer Lists
3488
+
3489
+ Constructor initializer lists can be all on one line or with subsequent lines indented four spaces.
3490
+
3491
+ The acceptable formats for initializer lists are:
3492
+ ```
3493
+ // When everything fits on one line:
3494
+ MyClass::MyClass(int var) : some_var_(var) {
3495
+ DoSomething();
3496
+ }
3497
+
3498
+ // If the signature and initializer list are not all on one line,
3499
+ // you must wrap before the colon and indent 4 spaces:
3500
+ MyClass::MyClass(int var)
3501
+ : some_var_(var), some_other_var_(var + 1) {
3502
+ DoSomething();
3503
+ }
3504
+
3505
+ // When the list spans multiple lines, put each member on its own line
3506
+ // and align them:
3507
+ MyClass::MyClass(int var)
3508
+ : some_var_(var), // 4 space indent
3509
+ some_other_var_(var + 1) { // lined up
3510
+ DoSomething();
3511
+ }
3512
+
3513
+ // As with any other code block, the close curly can be on the same
3514
+ // line as the open curly, if it fits.
3515
+ MyClass::MyClass(int var)
3516
+ : some_var_(var) {}
3517
+ ```
3518
+
3519
+ ## Namespace Formatting
3520
+
3521
+ The contents of namespaces are not indented.
3522
+
3523
+ [Namespaces](#Namespaces) do not add an extra level of indentation. For example, use:
3524
+ ```
3525
+ namespace {
3526
+
3527
+ void foo() { // Correct. No extra indentation within namespace.
3528
+ ...
3529
+ }
3530
+
3531
+ } // namespace
3532
+ ```
3533
+
3534
+ Do not indent within a namespace:
3535
+ ```
3536
+ namespace {
3537
+
3538
+ // Wrong! Indented when it should not be.
3539
+ void foo() {
3540
+ ...
3541
+ }
3542
+
3543
+ } // namespace
3544
+ ```
3545
+
3546
+ ## Horizontal Whitespace
3547
+
3548
+ Use of horizontal whitespace depends on location. Never put trailing whitespace at the end of a line.
3549
+
3550
+ **GENERAL**
3551
+ ```
3552
+ int i = 0; // Two spaces before end-of-line comments.
3553
+
3554
+ void f(bool b) { // Open braces should always have a space before them.
3555
+ ...
3556
+ int i = 0; // Semicolons usually have no space before them.
3557
+ // Spaces inside braces for braced-init-list are optional. If you use them,
3558
+ // put them on both sides!
3559
+ int x[] = { 0 };
3560
+ int x[] = {0};
3561
+
3562
+ // Spaces around the colon in inheritance and initializer lists.
3563
+ class Foo : public Bar {
3564
+ public:
3565
+ // For inline function implementations, put spaces between the braces
3566
+ // and the implementation itself.
3567
+ Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
3568
+ void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
3569
+ ...
3570
+ ```
3571
+
3572
+ Adding trailing whitespace can cause extra work for others editing the same file when they merge, as can removing existing trailing whitespace. So, don't introduce trailing whitespace. Remove it if you're already changing that line, or do it in a separate clean-up operation (preferably when no one else is working on the file).
3573
+
3574
+ **LOOPS AND CONDITIONALS**
3575
+ ```
3576
+ if (b) { // Space after the keyword in conditions and loops.
3577
+ } else { // Spaces around else.
3578
+ }
3579
+ while (test) {} // There is usually no space inside parentheses.
3580
+ switch (i) {
3581
+ for (int i = 0; i < 5; ++i) {
3582
+ // Loops and conditions may have spaces inside parentheses, but this
3583
+ // is rare. Be consistent.
3584
+ switch ( i ) {
3585
+ if ( test ) {
3586
+ for ( int i = 0; i < 5; ++i ) {
3587
+ // For loops always have a space after the semicolon. They may have a space
3588
+ // before the semicolon, but this is rare.
3589
+ for ( ; i < 5 ; ++i) {
3590
+ ...
3591
+
3592
+ // Range-based for loops always have a space before and after the colon.
3593
+ for (auto x : counts) {
3594
+ ...
3595
+ }
3596
+ switch (i) {
3597
+ case 1: // No space before colon in a switch case.
3598
+ ...
3599
+ case 2: break; // Use a space after a colon if there's code after it.
3600
+ ```
3601
+
3602
+ **OPERATORS**
3603
+ ```
3604
+ // Assignment operators always have spaces around them.
3605
+ x = 0;
3606
+
3607
+ // Other binary operators usually have spaces around them, but it's
3608
+ // OK to remove spaces around factors. Parentheses should have no
3609
+ // internal padding.
3610
+ v = w * x + y / z;
3611
+ v = w*x + y/z;
3612
+ v = w * (x + z);
3613
+
3614
+ // No spaces separating unary operators and their arguments.
3615
+ x = -5;
3616
+ ++x;
3617
+ if (x && !y)
3618
+ ...
3619
+ ```
3620
+
3621
+ **TEMPLATES AND CASTS**
3622
+ ```
3623
+ // No spaces inside the angle brackets (< and >), before
3624
+ // <, or between >( in a cast
3625
+ std::vector<std::string> x;
3626
+ y = static_cast<char*>(x);
3627
+
3628
+ // No spaces between type and pointer.
3629
+ std::vector<char*> x;
3630
+ ```
3631
+
3632
+ ## Vertical Whitespace
3633
+
3634
+ Use vertical whitespace sparingly; unnecessary blank lines make it harder to see overall code structure. Use blank lines only where they aid the reader in understanding the structure.
3635
+
3636
+ Do not add blank lines where indentation already provides clear delineation, such as at the start or end of a code block. Do use blank lines to separate code into closely related chunks, analogous to paragraph breaks in prose. Within a statement or declaration, usually only insert line breaks to stay within the [line length limit](#Line_Length), or to attach a comment to only part of the contents.
3637
+
3638
+ # Exceptions to the Rules
3639
+
3640
+ The coding conventions described above are mandatory. However, like all good rules, these sometimes have exceptions, which we discuss here.
3641
+
3642
+ ## Existing Non-conformant Code
3643
+
3644
+ You may diverge from the rules when dealing with code that does not conform to this style guide.
3645
+
3646
+ If you find yourself modifying code that was written to specifications other than those presented by this guide, you may have to diverge from these rules in order to stay consistent with the local conventions in that code. If you are in doubt about how to do this, ask the original author or the person currently responsible for the code. Remember that *consistency* includes local consistency, too.
3647
+
3648
+ ## Windows Code
3649
+
3650
+ Windows programmers have developed their own set of coding conventions, mainly derived from the conventions in Windows headers and other Microsoft code. We want to make it easy for anyone to understand your code, so we have a single set of guidelines for everyone writing C++ on any platform.
3651
+
3652
+ It is worth reiterating a few of the guidelines that you might forget if you are used to the prevalent Windows style:
3653
+
3654
+ * Do not use Hungarian notation (for example, naming
3655
+ an integer `iNum`). Use the Google naming
3656
+ conventions, including the `.cc` extension
3657
+ for source files.
3658
+ * Windows defines many of its own synonyms for
3659
+ primitive types, such as `DWORD`,
3660
+ `HANDLE`, etc. It is perfectly acceptable,
3661
+ and encouraged, that you use these types when calling
3662
+ Windows API functions. Even so, keep as close as you
3663
+ can to the underlying C++ types. For example, use
3664
+ `const TCHAR*` instead of
3665
+ `LPCTSTR`.
3666
+ * When compiling with Microsoft Visual C++, set the
3667
+ compiler to warning level 3 or higher, and treat all
3668
+ warnings as errors.
3669
+ * Do not use `#pragma once`; instead use
3670
+ the standard Google include guards. The path in the
3671
+ include guards should be relative to the top of your
3672
+ project tree.
3673
+ * In fact, do not use any nonstandard extensions,
3674
+ like `#pragma` and `__declspec`,
3675
+ unless you absolutely must. Using
3676
+ `__declspec(dllimport)` and
3677
+ `__declspec(dllexport)` is allowed; however,
3678
+ you must use them through macros such as
3679
+ `DLLIMPORT` and `DLLEXPORT`, so
3680
+ that someone can easily disable the extensions if they
3681
+ share the code.
3682
+
3683
+ However, there are just a few rules that we occasionally need to break on Windows:
3684
+
3685
+ * Normally we [strongly discourage
3686
+ the use of multiple implementation inheritance](#Multiple_Inheritance);
3687
+ however, it is required when using COM and some ATL/WTL
3688
+ classes. You may use multiple implementation
3689
+ inheritance to implement COM or ATL/WTL classes and
3690
+ interfaces.
3691
+ * Although you should not use exceptions in your own
3692
+ code, they are used extensively in the ATL and some
3693
+ STLs, including the one that comes with Visual C++.
3694
+ When using the ATL, you should define
3695
+ `_ATL_NO_EXCEPTIONS` to disable exceptions.
3696
+ You should investigate whether you can also disable
3697
+ exceptions in your STL, but if not, it is OK to turn on
3698
+ exceptions in the compiler. (Note that this is only to
3699
+ get the STL to compile. You should still not write
3700
+ exception handling code yourself.)
3701
+ * The usual way of working with precompiled headers
3702
+ is to include a header file at the top of each source
3703
+ file, typically with a name like `StdAfx.h`
3704
+ or `precompile.h`. To make your code easier
3705
+ to share with other projects, avoid including this file
3706
+ explicitly (except in `precompile.cc`), and
3707
+ use the `/FI` compiler option to include the
3708
+ file automatically.
3709
+ * Resource headers, which are usually named
3710
+ `resource.h` and contain only macros, do not
3711
+ need to conform to these style guidelines.