C/C ++ forced type conversion [zz]

Source: Internet
Author: User

C/C ++ forced type conversion

Q: What is C style conversion? What are static_cast, dynamic_cast, and reinterpret_cast? What is the difference? Why?

A: The meaning of conversion is to change the expression of a variable by changing its type to another type. To convert a simple object to another object of type conversion, you will use the traditional type conversion operator. For example, to convert a pointer of a floating point of the doubole type to an integer type:
Code:
Int I;
Double D;

I = (INT) D;
Or:

I = int (d );

It works well for simple types with standard definition conversions. However, such conversion characters can also be applied to Class and Class pointers indiscriminately. The ANSI-C ++ standard defines four new delimiters: 'reinterpret _ cast', 'static _ cast', 'dynamic _ cast', and 'const _ cast ', the purpose is to control the type conversion between classes.
Code:
Reinterpret_cast <new_type> (expression)
Dynamic_cast <new_type> (expression)
Static_cast <new_type> (expression)
Const_cast <new_type> (expression)

1 reinterpret_cast

'Reinterpret _ cast' converts a pointer to another type. It can also be converted from a pointer to an integer. And vice versa. Is the specific address value of the pointer an integer ?)
This operator can be converted between unrelated types. The operation result is simply a binary copy of the value from a pointer to another pointer. Do not check or convert any types of content that points between types.

If the situation is a copy from a pointer to an integer, the content is interpreted as system-related, so any implementation is not convenient. A pointer that can be converted to an integer that is large enough to contain it can be converted back to a valid pointer.

Code:
Class {};
Class B {};

A * A = new;
B * B = reinterpret_cast <B *> ();
'Reinterpret _ cast' treats all pointer type conversions just like traditional type conversions.

2 static_cast

'Static _ cast' allows you to perform any implicit conversion or reverse conversion. (Even if it does not allow implicit)

Applies to the class pointer, which means that it allows the pointer of the subclass type to be converted to the pointer of the parent class (this is a valid implicit conversion), and can also execute the opposite action: converts the parent class to its subclass.

In the final example, the converted parent class is not checked for consistency with the target type.
Code:
Class base {};
Class derived: public base {};

Base * A = new base;
Derived * B = static_cast <derived *> ();
In addition to Operation Type pointers, 'static _ cast' can also be used to execute Explicit conversions of Type Definitions and standard conversions between basic types:

Code:
Double D = 3.14159265;
Int I = static_cast <int> (d );

3 dynamic_cast

'Dynamic _ cast' is only used for object pointers and references. When used for polymorphism, it allows any implicit type conversion and the opposite process. However, unlike static_cast, dynamic_cast checks whether the operation is valid in the next case (note: the opposite process of implicit conversion. That is to say, it checks whether the conversion will return a valid complete object requested.
Check when running. If the converted pointer is not a valid and complete object pointer requested, the return value is null.
Code:
Class base {virtual dummy (){}};
Class derived: public base {};

Base * b1 = new derived;
Base * b2 = new base;

Derived * D1 = dynamic_cast <derived *> (B1); // succeeds
Derived * D2 = dynamic_cast <derived *> (B2); // fails: returns 'null'

If a reference type performs type conversion and this conversion is not possible, an exception type of bad_cast is thrown:
Code:
Class base {virtual dummy (){}};
Class derived: public base {};

Base * b1 = new derived;
Base * b2 = new base;

Derived d1 = dynamic_cast <derived & *> (B1); // succeeds
Derived D2 = dynamic_cast <derived & *> (B2); // fails: exception thrown

4 const_cast

This conversion type controls the const attribute of the passed object, or sets or removes the const attribute:
Code:
Class C {};

Const C * A = new C;

C * B = const_cast <C *> ();
The other three operators cannot modify the constants of an object.
Note: 'const _ cast' can also change a type of volatile qualifier.

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

Four types of C ++ Conversion

I. The forced transformation of C-style is as follows:

(T) expression // cast expression to be of type T
Function-style forces the transformation to use the following syntax:
T (expression) // cast expression to be of type T
There is no essential difference between the two forms. It is simply a question of where brackets are placed. I call these two forms the forced transformation of old-style.

Ii. Four forced transformation forms of C ++:

C ++ also provides four new forms of forced Transformation (commonly referred to as forced transformation of a new style or C ++ style ):
Const_cast (expression)
Dynamic_cast (expression)
Reinterpret_cast (expression)
Static_cast (expression)

Each option is applicable to a specific purpose:

· Dynamic _ cast is mainly used to execute "Safe downcasting", that is, to determine whether an object is a specific type in an inheritance system. It is the only force transformation that cannot be executed with the old style syntax, and is also the only force transformation that may have the price of a major operating era.

· Static _ cast can be used to force implicit conversions (for example, converting a non-const object to a const object, or converting an int to a double object ), it can also be used for many reverse conversions (for example, void * pointer transformation to type pointer, base class pointer transformation to derived class pointer ), however, it cannot transform a const object to a non-const object (only const_cast can do it), and it is closest to the C-style conversion.

· Const _ cast is generally used to forcibly remove constants of objects. It is the only forced transformation of the C ++ style that can achieve this.

· Reinterpret _ cast is specially used for underlying forced transformation, resulting in implementation-dependent (that is, cannot be transplanted) results. For example, a pointer is transformed into an integer. Such forced transformation should be extremely rare outside of the underlying code.
  
The forced transformation of the old style is still valid, but the new form is more desirable. First, they are easier to identify in the Code (whether it is a human or a tool like grep), which simplifies the process of finding where the type system is destroyed in the code. Second, more accurately specify the purpose of each forced transformation, making it possible for the compiler to diagnose usage errors. For example, if you try to use a new style other than const_cast to force transformation to eliminate constants, your code will not compile.

=
= Dynamic_cast. vs. static_cast
=

Class B {...};
Class D: Public B {...};

Void F (B * pb)
{
D * pd1 = dynamic_cast <D *> (PB );
D * Pd2 = static_cast <D *> (PB );
}

If PB really points to an object of Type D, then pd1 and Pd2 will get the same value. They will also get the same value if PB = 0.

If Pb points to an object of type B and not to the complete D class, then dynamic_cast will know enough to return zero. however, static_cast relies on the programmer's assertion that Pb points to an object of Type D and simply returns a pointer to that supposed
D object.

That is, dynamic_cast can be used for the downward transformation in the inheritance system, which converts the base class pointer to the derived class pointer, Which is stricter and safer than static_cast. Dynamic_cast has a lower execution efficiency than static_cast, but static_cast can perform ing in a wider range. This unrestricted ing is accompanied by insecurity. in addition to static navigation at the class level, the transformation types covered by static_cast also include non- ing transformations and narrow transformations (such transformations can cause object slicing and information loss ), use forced conversion of void *, implicit type conversion, etc...

=
= Static_cast. vs. reinterpret_cast
=

Reinterpret_cast is used to map to a completely different type. 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 xuanxu and other purposes, which is the most dangerous of all mappings. (This sentence is the original statement in C ++ programming ideas)

The static_cast and reinterpret_cast operators modify the operand type. they are not reciprocal. static_cast performs conversions using type information during compilation and performs necessary checks (such as cross-border pointer calculation and type check) during conversions ). the operands are relatively safe. on the other hand, reinterpret_cast only re-interprets the BIT model of the given object without binary conversion. The example is as follows:

Int n = 9; double D = static_cast <double> (N );

In the above example, 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 must complement the bitwise of the double-precision integer d correctly. the result is 9.0. the reinterpret_cast behavior is different:

Int n = 9;
Double D = reinterpret_cast <double &> (N );

This time, the results are different. After calculation, D contains useless values. This is because reinterpret_cast only copies N bits to D and does not perform necessary analysis.

 

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.