- 1. Implementations
- 1.1. Postpone variable definitions as long as possible until initial values can be provided
- 1.2. Minimize casting
- 1.3. Avoid returning “handles” to object internals
- 1.4. Strive for exception-safe code
- 1.5. Understand the ins and outs of inlining
- 1.6. Minimize compilation dependencies between files
(I read a Chinese version of the book, any translation problem plz point out.
- old-style casts
- C style cast:
- function style cast:
- C style cast:
- CPP style casts
- const_cast: cast away the constness.
- dynamic_cast: safe downcasting, to decide which type a object belongs to in the inheritance hierarchy.
- reinterpret_cast: low-level cast.
- static_cast: force implicit conversions.
- dynamic_casts maybe implement based on the comparision on string names of classes.
- try to hide the cast in a function, then provide to customers, once it is a must.
- do use the CPP style cast.
handles: references, pointers, iterators
try to use a copy
- no resources leak.
mutexwill never release.
- no data break.
bgImgwill point to a deleted object.
and the behavior of
imageChangeswill be weird, which it changed or not.
- basic promise.
when exception throws, everything is in a valid state, but the users can’t predict it.
- strong guarantee.
when exception throws, the program remains unchanged.
- nothrow guarantee
int doSomething() throw();
though the function throws nothing, it is not guaranteed. aka., if throws, it will be a fatal error,
unexpectedwill be called (Google
all the properties of the functions is decided by implementation, not the declaration.
- even if strong guarantee can be implemented by
copy and swap, but it is not implementable to all the functions. and watch the cost of copy.
- exception-safety is decided by the weakest one of all the functions.
- once you have no choice but to set no any guarantee (when you call
the old code), document it.
inlinejust applys for inling to compiler, not forcing to do so.
inlinethe minimal, frequently called functions.
inlinefunctions usually put in headers. because inlining happens in compiling period, compiler needs to know what they look like.
- the functions calls virtual functions will be never inlined, because virtual functions can only be known in run-time.
- think over before inling construtors and destrutors. maybe there are complicated codes generated by compilers.
pimpl idiom -> handle classes
abstract base class -> interface class
- don’t use objects, if object references or object pointers achieves.
- replace class definitions with class declarations as much as possible.
- provide declaration and definition with different headers.
use handle classes and interface classes to minimize changes for users during the develpment of program.
but replace with concrete classes, when the great difference in speed or size compared to coupling between classes.