C + + type conversion character and difference

Source: Internet
Author: User


Type conversions for C + +: static_cast, dynamic_cast, reinterpret_cast, and Const_cast

Use the standard C + + type conversion characters: static_cast, dynamic_cast, reinterpret_cast, and const_cast.

1 static_cast

Usage: static_cast < Type-id > (expression)

The operator converts expression to the Type-id type, but does not have run-time type checking to guarantee the security of the conversion. It is mainly used in the following ways:

① is used for the conversion of pointers or references between base and subclass classes in a class hierarchy.

It is safe to make an upstream conversion (a pointer or reference to a class is converted to a base class representation).

When a downstream conversion (a base class pointer or reference is converted to a subclass representation) is not secure because there is no dynamic type checking.

② is used for conversions between basic data types, such as converting int to char, and converting int to enum. The security of this conversion is also to be ensured by the developer.

③ converts a null pointer to a null pointer of the target type.

④ converts any type of expression to a void type.

Note: static_cast cannot convert the const, Volitile property of expression

2 dynamic_cast

Usage: dynamic_cast < Type-id > (expression)

This operator converts expression to an object of type Type-id. Type-id must be a pointer to a class, a reference to a class, or void *;

If Type-id is a class pointer type, then expression must also be a pointer, and if Type-id is a reference, then expression must also be a reference.

The dynamic_cast is primarily used for upstream and downstream conversions between class hierarchies, and can also be used for cross-conversion between classes.

The effect of dynamic_cast and static_cast is the same when the upstream conversion is performed between class hierarchies;

In the downstream conversion, dynamic_cast has the function of type checking, which is more secure than static_cast.

Class b{

Public

int m_inum;

virtual void foo ();

};

CL-D:public b{

Public

Char *m_szname[100];

};

void func (B *pb) {

D *PD1 = static_cast (PB);

D *PD2 = dynamic_cast (PB);

}

In the preceding code snippet, if PB points to an object of type D, PD1 and PD2 are the same, and any operation that performs type D on both pointers is safe;

However, if PB is pointing to an object of type B, then PD1 will be a pointer to that object, and the type D operation will be unsafe (such as access M_szname).

And PD2 will be a null pointer.

Also note: B to have virtual function, or compile error, static_cast There is no such limit.

This is because runtime type checking requires run-time type information, and this information is stored in the class's Virtual function table (

With regard to the concept of virtual function tables, in detail, only classes that define virtual functions have virtual function tables.

A class that does not have a virtual function defined is not a virtual function table.

In addition, the dynamic_cast supports cross-cast. As shown in the following code.

Class a{

Public

int m_inum;

virtual void F () {}

};

Class B:public a{

};

Class D:public a{

};

void Foo () {

b *PB = new B;

Pb->m_inum = 100;

D *PD1 = static_cast (PB); Compile error

D *PD2 = dynamic_cast (PB); PD2 is NULL

Delete PB;

}

In function foo, a conversion using static_cast is not allowed and will fail at compile time, whereas a conversion using dynamic_cast is allowed with the result of a null pointer.

3 reinterpret_cast

Usage: reinterpret_cast (expression)

Type-id must be a pointer, reference, arithmetic type, function pointer, or member pointer.

It can convert a pointer to an integer, or convert an integer to a pointer (a pointer is converted to an integer first,

The original pointer value can also be obtained when the integer is converted to a pointer of the original type.

The operator uses more.

(Compare static_cast with reinterpret_cast, see below)

4 const_cast

Usage: const_cast (expression)

The operator is used to modify the const or volatile properties of a type. In addition to const or volatile adornments, the type_id and expression types are the same.

The constant pointer is converted into a very pointer, and still points to the original object;

A constant reference is converted to a very literal reference and still points to the original object, and the constant object is converted to a very mass object.

Voiatile and const are similar. As an example:

Class b{

Public

int m_inum;

}

void Foo () {

Const B B1;

B1.m_inum = 100; Comile Error

B B2 = const_cast (B1);

B2. M_inum = 200; Fine

}

The above code compiles with an error, because B1 is a constant object and cannot be changed;

By using const_cast to convert it to a constant object, you can arbitrarily change its data members. Note: B1 and B2 are two different objects.

== ===========================================

= = dynamic_cast vs. static_cast

== ===========================================

Class B {...};

Class D:public B {...};

void F (b* pb)

{

d* PD1 = dynamic_cast (PB);

d* PD2 = static_cast (PB); }

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. The 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. In addition to the static navigation of the class hierarchy, the transformation types covered by static_cast include no-mapping transformations, narrow transformations (which can result in object slicing, loss of information), forced transformations with void*, implicit type transformations, etc.

== ===========================================

= = 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 just for the sake of the 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 reciprocal; static_cast uses type information to perform transformations at compile time, performing the necessary checks on transformations (such as pointer out-of-bounds calculations, type checking). The operands are relatively safe. Reinterpret_cast, on the other hand, simply re-interprets the given object's bit model without binary conversion, as 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, 9,static_cast needs to correctly complement the bit for the double-precision integer d. The result is 9.0. And Reinterpret_cast's behavior is different:

int n=9;

Double D=reinterpret_cast (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.

This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1829207

C + + type conversion character and difference

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.