4 types of conversion modes in C + + cast operation detailed _c language

Source: Internet
Author: User
Tags inheritance

Q: What is C-style conversion? What is Static_cast,dynamic_cast and reinterpret_cast? What's the difference? Why pay attention to it?

A: The meaning of a transformation is to change the representation of the variable by changing the type of the variable to another type. To convert a simple object for a type to another object you will use the traditional type conversion operator. For example, to convert a pointer to a type doubole floating-point number to an integral type:
Code:
Inti
doubled;

i= (int) D;
Or:

I=int (d);

Works well for simple types with standard definition conversions. However, such a converter can also be applied to classes (class) and to pointers to classes in an indiscriminate way. The ansi-c++ standard defines four new conversions: ' Reinterpret_cast ', ' static_cast ', ' dynamic_cast ' and ' const_cast ', which are designed to control type conversions between classes (Class).
Code:
reinterpret_cast<new_type> (expression)
dynamic_cast<new_type> (expression)
static_cast<new_type> (expression)
const_cast<new_type> (expression)

1reinterpret_cast

' Reinterpret_cast ' converts a pointer to another type of pointer. It also allows you to convert from one pointer to an integer type. Vice versa. Is the pointer a specific address value as an integer value? )
This operator can be converted between unrelated types. The result of the operation is simply a binary copy of the value from one pointer to another pointer. The content pointed to between types does not do any type of checking and conversion.

If the situation is a copy from a pointer to an integral type, the interpretation of the content is system-related, so any implementation is not convenient. A pointer that converts to a large enough size to contain it can be converted back to a valid pointer.

Code:
classa{};
classb{};

A*a=newa;
B*b=reinterpret_cast<b*> (a);
' Reinterpret_cast ' treats all pointer type conversions like traditional type conversions.

2static_cast

' static_cast ' allows arbitrary implicit conversions and reverse conversion actions to be performed. (even if it is not allowed to be implicit)

Applied to a pointer to a class, meaning that it allows a pointer of a subclass type to be converted to a pointer to the parent class type (this is a valid implicit conversion), and can also perform the opposite action: convert the parent class to its subclass.

In this final example, the converted parent class is not checked for consistency with the destination type.
Code:
classbase{};
classderived:publicbase{};

Base*a=newbase;
Derived*b=static_cast<derived*> (a);
' Static_cast ' can also be used to perform explicit conversions of type definitions and standard conversions between underlying types, in addition to manipulating type pointers:

Code:
doubled=3.14159265;
Inti=static_cast<int> (d);

3dynamic_cast

' dynamic_cast ' is used only for pointers and references to objects. When used with polymorphic types, it allows arbitrary implicit type conversions as well as the opposite process. However, unlike static_cast, in the latter case (note: The reverse process of an implicit conversion), dynamic_cast checks to see if the operation is valid. That is, it checks whether the conversion returns a valid, full object that is being requested.

Detection is performed at run time. If the converted pointer is not a valid, full object pointer to the request, the return value is null.
Code:
Classbase{virtualdummy () {}};
classderived:publicbase{};

base*b1=newderived;
Base*b2=newbase;

Derived*d1=dynamic_cast<derived*> (B1);//succeeds
Derived*d2=dynamic_cast<derived*> (B2);//fails:returns ' NULL '

If a reference type performs a type conversion and this conversion is not possible, an Bad_cast exception type is thrown:
Code:
Classbase{virtualdummy () {}};
classderived:publicbase{};

base*b1=newderived;
Base*b2=newbase;

Derivedd1=dynamic_cast<derived&*> (B1);//succeeds
Derivedd2=dynamic_cast<derived&*> (B2);//fails:exceptionthrown

4const_cast

This conversion type manipulates the Const property of the passed object, or it is set or removed:
Code:
classc{};

CONSTC*A=NEWC;

C*b=const_cast<c*> (a);
The other three operators cannot modify the constants of an object.
Note: ' Const_cast ' can also change a type of volatilequalifier.

--------------------------------------------------------------------

4 Types of conversions for C + +

A, C style (C-style) mandatory transformation as follows:

(T) Expression//castexpressiontobeoftypet
Functional Style (Function-style) forced transformation using such syntax:
T (expression)//castexpressiontobeoftypet
There is no intrinsic difference between the two forms, which is simply a question of where to put the parentheses. I refer to these two forms as the compulsory transformation of the old Style (Old-style).

Second, C + + four forms of compulsory transformation:

C + + also offers four new forms of forced transformation (often called new-style or C + +-style forced transitions):
Const_cast (expression)
dynamic_cast (expression)
reinterpret_cast (expression)
static_cast (expression)

Each one applies to a specific purpose:

dynamic_cast is primarily used to perform a "secure downward Transition (safedowncasting)", that is, to determine whether an object is a specific type in an inheritance system. It is the only mandatory transition that cannot be performed with the old style syntax, and the only mandatory transition that can have significant run-time costs.

static_cast can be used to force implicit conversions (for example, a Non-const object transforms to a const object, int transforms to a double, and so on), and it can also be used for the reverse conversion of many of these transformations (for example, the void* pointer transitions to a type pointer, The base class pointer transitions 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.

const_cast is generally used to enforce the elimination of constants of objects. It is the only one that can do this with a C-style mandatory transformation.

reinterpret_cast is deliberately used for low-level forced transitions, resulting in the implementation of dependencies (i.e., not porting) results, for example, transforming a pointer to an integer. Such a forced transition should be extremely rare beyond the underlying code.

The forced transformation of the old style is still legal, but the new form is preferable. First, they are easier to identify in your code (as is the case with tools like grep), which simplifies the process of finding out where the type system is corrupted in your code. Second, specifying the purpose of each mandatory transition more precisely makes it possible for the compiler to diagnose using errors. For example, if you try to use a new style other than const_cast to force transitions to eliminate the constant, your code will not compile.

==
==dynamic_cast.vs.static_cast
==

Classb{...};
Classd:publicb{...};

VOIDF (B*PB)
{
D*pd1=dynamic_cast<d*> (PB);
D*pd2=static_cast<d*> (PB);
}

Ifpbreallypointstoanobjectoftyped,thenpd1andpd2willgetthesamevalue. Theywillalsogetthesamevalueifpb==0.

Ifpbpointstoanobjectoftypebandnottothecompletedclass,thendynamic_castwillknowenoughtoreturnzero. However,static_ Castreliesontheprogrammer ' Sassertionthatpbpointstoanobjectoftypedandsimplyreturnsapointertothatsupposeddobject.

That is, dynamic_cast can be used for the downward transition in the inheritance system, and the base class pointer is converted to a derived class pointer, which is more secure and more rigorous than the static_cast. Dynamic_cast is less efficient than static_cast, but static_cast can complete the mapping in a wider range, an unrestricted mapping with no security. Static_cast Overridden Transformation Types in addition to static navigation at the class level, Also includes the unmapped transformation, the narrowing transformation (this transformation can cause the object slice, loses the information), uses the void* transformation, the implicit type transformation and so on ...


==
==static_cast.vs.reinterpret_cast
==

Reinterpret_cast is 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 myth and other purposes, which is the most dangerous of all mappings. (This sentence is the language of C + + programming Thinking)

The static_cast and reinterpret_cast operators modify the operand type. They are not reciprocal; The static_cast performs the conversion using type information at compile time, performing the necessary instrumentation (such as pointer-crossing calculations, type checking) in the transformation. Its operands are relatively safe. On the other hand, reinterpret_cast merely interprets the given object's bit model without a binary conversion, as the following examples are:

Intn=9;doubled=static_cast<double> (n);

In the example above, we convert a variable from int to double. These types of binary expressions are different. To convert an integer 9 to a double-precision integer 9,static_cast you need to properly complement the bits with a double-precision integer d. The result is 9.0. and reinterpret_ The behavior of cast is different:

intn=9;
Doubled=reinterpret_cast<double&> (n);

This time, the results are different. After the calculation, D contains the useless value. This is because the reinterpret_cast is simply copying n bits to D, without making the necessary analysis.

Summarize:

There are four cast species altogether.
1, static_cast, support the subclass pointer to the parent class pointer conversion, and according to the actual situation to adjust the value of the pointer, in turn support, but will give a compiler warning, it functions most similar to the C-style "forced conversion", generally speaking, it is safe;

2, dynamic_cast, support the parent class pointer to the subclass of the pointer conversion, and according to the actual situation to adjust the value of the pointer, 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 it is simply "Columa" as its name describes, and does not make any adjustments to the value of the pointer, and it is perfectly possible to "make it", but it is obvious that it is the most unsafe conversion, when you use it, you have to be clear-headed, Know what you're doing;

4, const_cast, this transformation can be stripped of the const attribute of an object, which means that you are allowed to modify constants.

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.