Item 1: Treat C++ as a federation of languages#
In addition to the four programming paradigms of procedural, object-oriented, template, and functional programming, there is also metaprogramming, which can be included in generic programming, namely templates; the STL is an exemplar of metaprogramming.
- Ways to experience learning C++
Item 2: Prefer const/enum/inline to #define#
If possible, avoid using #define for the sake of debugging convenience; using define can easily hide errors because all macros are invisible to the compiler.
- For simple constants, it is best to use const objects or enums.
- For macro-like functions, it is best to use inline functions.
Item 3: Use const whenever possible#
Const in terms of data meaning vs. const in terms of logical meaning
- The former is enforced by the compiler, while the latter is used by us when writing programs.
- The former: true const in terms of data meaning is difficult to achieve and involves pointers, which can change the data through other means.
- The latter: if the core data hasn't changed, it can be considered const in terms of logical meaning.
PS: const objects and methods
- Const objects: cannot call non-const methods because variables inside non-const methods may change.
- Const methods
- Cannot modify member attributes internally.
- Mutable variables: const in terms of logic, although the variable can be changed, it is not core data.
Item 4: Make sure that objects are initialized before they are used#
- Manually initialize built-in objects.
- C++ does not guarantee the initialization of built-in objects.
- It is best to use initialization lists for constructor assignment.
- Initialization lists call the constructor.
- Constructors and assignment operators are completely different concepts in C++.
- Constructors are mainly responsible for object initialization.
- The order of members listed in the initialization list should be consistent with their order of declaration in the class.
- The visible order is the actual order, which is convenient for maintenance.
- Even if written in reverse, the program still initializes variables in the order of declaration.
- Reduce the "initialization order across translation units" problem by replacing non-local static objects with local static objects.
- Minimize dependencies on cross-file initialization.