Bo2SS

Bo2SS

Effective C++ Reading Share

Item 1: View C++ as a Language Federation#

In addition to the four programming paradigms of procedure, object, template, and function, there is also metaprogramming, which can be included in generic programming, namely templates; STL is a paradigm of metaprogramming.

  • Experience the way of learning C++

Item 2: Prefer const/enum/inline over #define#

Avoid using #define when possible for easier debugging; using define can easily mask errors because all macros are invisible to the compiler.

  1. For pure constants, it is best to use const objects or enums.
  2. For macros that resemble functions, it is best to use inline functions.

Item 3: Use const as much as possible#

Data-level const VS. logical-level const

  • The compiler enforces the former, while we use the latter when writing programs.
  • The former: true data-level const is difficult to achieve, involving pointers, and data may be changed in other ways.
  • The latter: if the core data hasn't changed, it can be considered logical-level const.

PS: const objects and methods

image-20210707184228548
  • const objects: cannot call non-const methods because variables within non-const methods may change.
  • const methods
    • Cannot modify member properties internally.
    • mutable variables: logically const, although the variable can change, it is not core data.

Item 4: Ensure objects are initialized before use#

  1. Manually initialize built-in type objects.
  • C++ does not guarantee that built-in type objects will be initialized.
  1. It is best to use an initializer list for constructor assignments.
image-20210707184301293
  • The initializer list calls the constructor.
    • Constructors and assignment operators are completely different concepts in C++.
    • Constructors are primarily responsible for object initialization.
  • The order of members listed in the initializer list should match the order in which they are declared in the class.
    • The order seen is the actual order, making maintenance easier.
    • Even if written in reverse, the program still initializes variables in the order of declaration.
  • Reduce the "initialization order across compilation units" issue by replacing non-local static objects with local static objects.
    • Minimize cross-file initialization dependencies.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.