You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
book: write Appendix 2 (modern C++ best practices)
Replace the TODO stubs with concrete, widely-accepted best practices
across tools, coding style, performance, safety, maintainability, and
portability. Reword the intro to reference the C++ Core Guidelines and
frame the content as generally accepted practice rather than secret
tips. Refs #1
Copy file name to clipboardExpand all lines: book/en-us/appendix2.md
+30-7Lines changed: 30 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,31 +6,54 @@ order: 12
6
6
7
7
# Appendix 2: Modern C++ Best Practices
8
8
9
-
In this appendix we will briefly talk about the best practices of modern C++. In general, the author's thoughts on C++'s best practices are mainly absorbed from [Effective Modern C++](https://www.amazon.com/dp/1491903996/ref=cm_sw_em_r_mt_dp_U_-ZgjDb81ERBNP) and [C++ Style Guide](https://google.github.io/styleguide/cppguide.html). In this appendix, we will briefly discuss and use the actual examples to illustrate the methods, and introduce some of **the author's personal**, **non-common**, **non-sensible** best practices, and how to ensure the overall quality of the code.
9
+
In this appendix we briefly discuss the best practices of modern C++. Many of these ideas are distilled from [Effective Modern C++](https://www.amazon.com/dp/1491903996/) and the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html), as well as the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) maintained by Bjarne Stroustrup and Herb Sutter. The goal of this appendix is to summarize widely accepted practices that help ensure the overall quality of your code.
10
10
11
11
## Common Tools
12
12
13
-
TODO:
13
+
Good tooling catches a large class of problems before they ever reach production:
14
+
15
+
-**Enable warnings, and treat them as errors.** Compile with `-Wall -Wextra` (and consider `-Wpedantic`); `-Werror` keeps warnings from accumulating.
16
+
-**Run sanitizers during testing.** AddressSanitizer (`-fsanitize=address`), UndefinedBehaviorSanitizer (`-fsanitize=undefined`) and ThreadSanitizer (`-fsanitize=thread`) catch memory errors, undefined behavior, and data races at run time.
17
+
-**Format and lint automatically.**`clang-format` keeps style consistent, and `clang-tidy` flags bug-prone patterns and suggests modernizations.
18
+
-**Use a modern build system and package manager**, such as CMake together with vcpkg or Conan, to make builds reproducible.
19
+
-**Experiment quickly** with [Compiler Explorer](https://godbolt.org/) to inspect the generated assembly and compare compilers and standards.
14
20
15
21
## Coding Style
16
22
17
-
TODO:
23
+
A consistent style makes a codebase far easier to read and maintain:
24
+
25
+
- Pick a style guide and apply it consistently across the whole project; consistency matters more than the specific choices.
26
+
- Be `const`-correct: mark variables, member functions, and parameters `const` whenever they do not need to mutate state.
27
+
- Use `auto` to avoid redundant type spelling, but not at the cost of readability — keep the reader able to tell what a name means.
28
+
- Prefer the standard library (containers, algorithms, `std::string`) over hand-rolled equivalents.
18
29
19
30
## Overall Performance
20
31
21
-
TODO:
32
+
-**Measure before you optimize.** Use a profiler to find the real hot spots instead of guessing; premature optimization wastes effort and harms readability.
33
+
-**Avoid unnecessary copies.** Pass large objects by `const&`, or take by value and `std::move` when you need a copy anyway; `reserve()` containers when the final size is known.
34
+
-**Let the compiler help.** Return local objects by value and rely on (guaranteed) copy elision rather than returning via output parameters.
35
+
- Prefer move semantics for expensive-to-copy types, and remember that `std::move` is a cast, not an operation.
22
36
23
37
## Code Security
24
38
25
-
TODO:
39
+
-**Manage resources with RAII.** Wrap every resource (memory, files, locks, sockets) in an object whose destructor releases it.
40
+
-**Prefer smart pointers** (`std::unique_ptr`, `std::shared_ptr`) over raw `new`/`delete`; avoid owning raw pointers.
41
+
-**Avoid undefined behavior**: no out-of-bounds access, no signed overflow, no use-after-free, no strict-aliasing violations (see §9.5). Sanitizers help detect these.
42
+
- Prefer `std::span`, `std::array`, and `.at()` over raw pointers and unchecked indexing when bounds matter, and avoid C-style casts in favor of the named C++ casts.
26
43
27
44
## Maintainability
28
45
29
-
TODO:
46
+
- Keep functions small and focused on a single responsibility; prefer standard algorithms over hand-written loops to express intent clearly.
47
+
- Make interfaces hard to misuse: use strong types and enum classes instead of bare `int`/`bool` flags.
48
+
- Write tests, and run them continuously so regressions are caught early.
49
+
- Document *why*, not *what*: the code already says what it does.
30
50
31
51
## Portability
32
52
33
-
TODO:
53
+
- Use fixed-width integer types (`std::int32_t`, etc.) from `<cstdint>` when the exact size matters; do not assume `int` is 32 bits or that `char` is signed.
54
+
- Avoid implementation-defined and platform-specific behavior; when you must depend on it, isolate it behind a small abstraction.
55
+
- Prefer the standard library over platform-specific APIs (e.g. `<filesystem>`, `<thread>`, `<chrono>`) so the same code builds across platforms.
56
+
- When byte order matters, query it explicitly (`std::endian` in C++20) rather than assuming little- or big-endian.
34
57
35
58
[Table of Content](./toc.md) | [Previous Chapter](./appendix1.md)
Copy file name to clipboardExpand all lines: book/zh-cn/appendix2.md
+30-7Lines changed: 30 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,31 +6,54 @@ order: 12
6
6
7
7
# 附录 2:现代 C++ 的最佳实践
8
8
9
-
这篇附录我们来简单谈一谈现代 C++ 的最佳实践。总的来说,笔者关于 C++ 的最佳实践相关的思考主要吸收自[《Effective Modern C++》](https://www.amazon.cn/dp/B016OFO492/ref=sr_1_3?ie=UTF8&qid=1525613457&sr=8-3&keywords=Effective+C%2B%2B)和 [《C++ 风格指南》](http://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/contents/)。在这篇附录里将简单讨论、并使用实际例子来阐明的方法,介绍一些笔者**个人的**、**不是随处可见的**、**非常识性**的最佳实践,并如何保证代码的整体质量。
9
+
这篇附录我们来简单谈一谈现代 C++ 的最佳实践。这里的许多思考主要吸收自[《Effective Modern C++》](https://www.amazon.cn/dp/B016OFO492/)、[《C++ 风格指南》](http://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/contents/),以及由 Bjarne Stroustrup 与 Herb Sutter 维护的 [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines)。本附录旨在总结一些被广泛认可的最佳实践,帮助你保证代码的整体质量。
0 commit comments