[Effective C + +--027] Try to do less transformational action

Source: Internet
Author: User

Introduction

C-style transformational action

(t) expression     //  transform expression to T

The transformational action of the function style looks like this

T (expression)   //  transform expression to T

Four types of transformation in C + + style

Const_cast<t>(expression) dynamic_cast<T>(expression) reinterpret_cast<T> (expression) static_cast

Section one differences in C + + transformation

? Const_cast is generally used to force the elimination of the constants of an object. It is the only one that can do this with the C + + style of coercion.

The dynamic_cast is primarily used to perform "safe downcasting", that is, to determine whether an object is a specific type in an inheritance system. It is the only forced transformation that cannot be performed with the old style syntax, and it is the only forced transformation that can have significant runtime costs.
The reinterpret_cast is intended for the underlying forced transformation, resulting in the implementation of dependency (Implementation-dependent) (that is, non-portable) results, such as transforming a pointer to an integer. Such a forced transformation should be extremely rare outside of the underlying code.

The static_cast can be used to force implicit conversions (for example, the Non-const object is transformed to a const object, an int to a double, and so on), and it can also be used for a number of reverse transformations of such conversions (for example, the void* pointer is transformed into a typed pointer, The base class pointer is transformed to a derived class pointer), but it cannot transform a const object into a Non-const object (only const_cast can), which is closest to the C-style conversion.

Difference:

Dynamic_cast can be used to transform downward in the inheritance system, converting the base class pointer to a derived class pointer, which is stricter and more secure than the static_cast. Dynamic_cast is less efficient than static_cast, but the static_cast can be mapped in a wider range, and this unrestricted mapping is accompanied by insecurity. The type of transformation that the static_cast overrides, in addition to static navigation at the class level, Also includes the non-mapping transform, the narrowing transformation (this kind of transformation causes the object to slice, loses the information), uses the void* the forced transformation, the implicit type transformation and so on.

Reinterpret_cast is meant to map to a completely different type of meaning, and this keyword is used when we need to map the type back to the original type. The type we map to is only for the sake of trick and other purposes, which is the most dangerous of all mappings. (This is the exact words in C + + programming Idea)

The static_cast and reinterpret_cast operators modify the operand type. They are not mutually reversible; Static_cast uses type information at compile time to perform transformations that perform the necessary checks (such as pointer out-of-bounds calculations, type checking) on transformations. The operands are relatively safe. On the other hand, reinterpret_cast simply re-interprets the given object's bit model without binary conversion.

Summarize:

1,static_cast, support the sub-class pointer to the parent class pointer conversion, and adjust the value of the pointer according to the actual situation, but also support, but will give a compilation warning, it acts most like the C-style "cast", in general, it is considered to be safe;

2,dynamic_cast, support the parent class pointer to the child class pointer conversion, and adjust the value of the pointer according to the actual situation, and static_cast different, in turn it does not support, will lead to compile errors, this conversion is the most secure conversion;

3,reinterpret_cast, support any conversion, but just as the name of the description of the "Re-interpretation" only, do not make any adjustments to the value of the pointer, with it can be completely "presstitute", but it is clear that it is the most unsafe conversion, when using it, You have to be clear-headed and know what you are doing.

4,const_cast, this conversion can peel off the Const property of an object , that is, allow you to modify the constants.

< Span lang= "en-US" > second section transformation use                                        ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp            

Let's say we have the following code

1 class Base {...}; 2 class  Public Base {...}; 3 Derived D; 4 base* PB = &d;           // The metaphor transforms the derived* into a base*

In the above code, we set up a base class pointer to a derived class object, but sometimes the values of the two pointers above are not the same. In this case, an offset is applied to the derived pointer during operation to obtain the correct base* pointer value.

This means that a single object (such as a derived class object) may have more than one address (such as the address when base* points to it and the address when derived* points to it). In fact, once multiple inheritance occurs, this happens all the time.

It is important to note that the offset above is different from the compiler.

When calling the virtual function of the base class, it is also easy to get the following problems:

Requirement: When a virtual function is defined in both the base class and the derived class, if we want to invoke the function of the parent class in the derived class.

1 classBase {2  Public:3     Virtual voidonResize () {...};4 };5 6 classDevice: PublicBase {7  Public:8VirtualvoidonResize () {9         static_cast<base> (*this). OnResize ();//calling the OnResize function of the base class is actually not feasibleTen         ... One     } A};

In the red code, *this transforms to base, calling Base::onresize. However, it does not invoke a function on the current object, but rather a copy of the "base Class" of the *this object created by the earlier transition action.

The change method is very simple, take off the transformation, the direct call can:

1 classBase {2  Public:3     Virtual voidonResize () {...};4 };5 6 classDevice: PublicBase {7  Public:8     Virtual voidonResize () {9         base::onresize ();//Call the OnResize function of the base classTen         ... One     } A};

In this section, the author also describes two ways to avoid transformation, in fact the principle is the same: direct call, avoid too much transformation!

Summary

1. If possible, avoid transformation, especially in efficiency-focused code, avoiding the use of dynamic_cast

2. If you have to transform, try to hide it behind a function

3. Prefer to use the new C + + conversion without the old-fashioned transformation

[Effective C + +--027] Try to do less transformational action

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.