Article 27: Minimize transformation actions
One of the design goals of C ++ rules is to ensure that "type errors" are impossible. Unfortunately, the transformation (casts) destroys the type system. That could be
This may cause any type of trouble, some of which are easy to identify and some are very obscure.
The C-style transformation action looks like this:
(T) expression // convert expression to T
Function-style transformation actions look like this:
T (expression) // convert expression to T
C ++ also provides four new transformations:
Const_cast: it is usually used to convert the object's constants to the Division; that is, remove the const.
Dynamic_cast: Mainly used to perform "secure downward transformation", that is, to determine whether an object belongs to a type in the inheritance system.
Reinterpret_cast: it is intended to perform a low-level transformation. The actual action may depend on the compiler, which means it cannot be transplanted.
Static_cast: used to force implicit conversion, such as converting non-const to const, int to double, and so on.
Try to use the new type of Transformation:
· They are easily identified in the code, which simplifies the process of "finding out where the type system is destroyed.
· The narrower the targets of various transformation actions, the more likely the compiler will diagnose the wrong application.
Remember:
· If possible, avoid transformation as much as possible, especially avoid dynamic_casts in efficiency-oriented code. If there is a design that requires transformation, try to develop
There is no need for alternative designs for transformation.
· If transformation is necessary, try to hide it behind a function. The customer can then call this function without putting the transformation into their own code.
.
· We would rather use the C ++-style (New style) transformation than the old style transformation. The former is easy to identify, and has a different class of management.