Four types of cast operators for C + +

Source: Internet
Author: User

The difference between the four cast operators of C + +
Sending station: Water Wood Community (Thu Jan 26 21:15:16 2006), station

Declaration by NETMD:
Not my original, from the Internet, and is a collection of two posts, personally think this is more complete

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

Q: What is C-style conversion? What are static_cast, dynamic_cast and reinterpret_cast? What's the difference? Why should you pay attention?

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

i = (int) d;
Or:

i = int (d);

Works well for simple types that have standard definition transformations. However, such a translator can also be applied to classes (class) and class pointers without indiscriminate. The ansi-c++ standard defines four new conversions: ' Reinterpret_cast ', ' static_cast ', ' dynamic_cast ' and ' const_cast ', to control the type conversion between classes (Class).
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 of pointer. It also allows conversion from one pointer to an integer type. Vice versa. Is the pointer specific address value as an integer value? )
This operator can be converted between non-related types. The result of the operation is simply a binary copy of the value from one pointer to another pointer. Content that is pointed to between types does not have any type of check and conversion.

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

Code:
Class A {};
Class B {};

A * a = new A;
b * b = reinterpret_cast<b *> (a);
' Reinterpret_cast ' treats the type conversions of all pointers as if they were traditional type conversions.

2 static_cast

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

Applied to a pointer to a class, meaning that it allows a pointer of the subclass type to be converted to a pointer of 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:
Class Base {};
Class Derived:public Base {};

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

Code:
Double d = 3.14159265;
int i = static_cast<int> (d);

3 dynamic_cast

' dynamic_cast ' is used only for pointers and references to objects. When used with polymorphic types, it allows arbitrary implicit type conversions and the reverse process. However, unlike static_cast, in the latter case (note: The reverse process of implicit conversion), dynamic_cast checks whether the operation is valid. That is, it checks whether the transformation returns a valid full object that is requested.
The detection occurs at run time. If the pointer being converted is not a valid full object pointer being 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 a type conversion and this conversion is not possible, an Bad_cast exception type 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 manipulates the Const property of the passed object, or is either set or removed:
Code:
Class C {};

Const C *A = new C;

C *b = Const_cast<c *> (a);
The other three types of operators cannot modify the constant nature of an object.
Note: ' Const_cast ' can also change a type of volatile qualifier.

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

4 types of C + + conversions

A, C style (C-style) Forced transformation is as follows:

(t) expression/cast expression to BES of type T
The function style (function-style) Force transformation uses this syntax:
T (expression)//cast expression to be of type T
There is no intrinsic difference between the two forms, which is purely a question of where to put the brackets. I refer to these two forms as the forced transformation of the old Style (Old-style).

Ii. Four forms of compulsory transformation of C + +:

C + + also offers four new forms of forced transformation (often referred to as a new style or C + + style of forced transformation):
Const_cast (expression)
dynamic_cast (expression)
reinterpret_cast (expression)
static_cast (expression)

Each one is suitable for a specific purpose:

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.

static_cast can be used to force implicit conversions (for example, a Non-const object 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.

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.

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 into an integer. Such a forced transformation should be extremely rare outside of 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 code (both people and tools like grep), simplifying the process of finding where type systems are broken in code. Second, specifying the purpose of each forced transformation more precisely makes it possible for the compiler to diagnose the use of errors. For example, if you try to use a new style other than const_cast to force the transformation to eliminate the 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 a object of type D, then PD1 and PD2 would get the same value. They would also get the same value if PB = = 0.

If PB points to a object of type B and not to the complete D class, then dynamic_cast'll 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 point Er to that supposed D object.

That is, dynamic_cast can be used for a downward transformation in the inheritance system, converting a base-class pointer to a derived class pointer, which is stricter and more secure than 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 ...


==
= = Static_cast vs. reinterpret_cast
==

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, as shown in the following example:

int n=9; Double D=static_cast < double > (n);

In the example above, we convert a variable from int to a double. These types of binary expressions are different. To convert an integer 9 to a double integer of 9, static_cast needs to correctly complement the bit for the double integer d. The result is 9.0. And Reinterpret_cast's behavior is different:

int n=9;
Double d=reinterpret_cast<double & > (n);

This time, the results are different. After the calculation, D contains a useless value. This is because reinterpret_cast only replicates n bits to D and does not perform the 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.