Summarize all the cast functions in C + + (Const_cast,reinterpret_cast,static_cast,dynamic_cast)

Source: Internet
Author: User
Tags volatile

Take a note: from the Forum: http://bbs.csdn.net/topics/210039564


Summarize all the cast functions in C + + (Const_cast,reinterpret_cast,static_cast,dynamic_cast)


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).

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

3.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, Volitale, or __unaligned properties of expression.


3.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 ();
};

Class D:public b{
Public
Char *m_szname[100];
};

void func (B *pb) {
D *PD1 = Static_cast<d *> (pb);
D *pd2 = Dynamic_cast<d *> (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 <inside C + + object model>, 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<d *> (pb); Compile error
D *pd2 = Dynamic_cast<d *> (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.3 Reinpreter_cast
Usage:reinpreter_cast<type-id> (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.

3.4 const_cast
Usage:const_cast<type_id> (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 class test. As an example:
Class b{
Public
int m_inum;
}
void Foo () {
Const B B1;
B1.m_inum = 100; Comile Error
B B2 = const_cast<b> (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<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. 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<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.

Therefore, you need to be cautious about using reinterpret_cast.
#
# There are four main types of cast operators in standard C + +:
#
# Const_cast,reinterpret_cast,static_cast,dynamic_cast et cetera.
#
#
#
#
# 1) static_cast<t*> (a)
#
# Converting address A to type t,t and a must be pointers, references, arithmetic types, or enumeration types.
#
# expression static_cast<t*> (a), the value of a is converted to the type T specified in the template. During the run-time conversion process, no type checking is performed to ensure the security of the conversion.
#
#
#
#
Example
#
#
#
#
# class B {...};
#
# class D:public B {...};
#
# void F (b* pb, d* PD)
#
# {
#
# d* PD2 = static_cast<d*> (PB); Not safe, PB may just be a pointer to B
#
#
#
#
# b* PB2 = static_cast<b*> (PD); Safe for
#
#     ...
#
# }
#
#

# 2) dynamic_cast<t*> (a)
#
# Complete the promotion in the class hierarchy. T must be a pointer, reference, or untyped pointer. A must be an expression that determines a pointer or reference.
#
# expression dynamic_cast<t*> (a) converts a value to an object pointer of type T. If the type T is not a base type of a, the operation returns a null pointer.
#
#
#
#
Example
#
# class A {...};
#
# class B {...};
#
# void F ()
#
# {
#
# A * pa = new A;
#
# b* PB = new B;
#
# void* PV = dynamic_cast<a*> (PA);
#
#//PV now points to an object of type a
#
#    ...
#
# PV = dynamic_cast<b*> (PB);
#
#//PV now points to an object of type B
#
# }
#
#
#
#
# 3) const_cast<t*> (a)
#
# to remove constants from a type, the T and a must be of the same type, except for const or unstable variable addresses.
#
The # expression const_cast<t*> (a) is used to remove these properties from a class: const, volatile, and __unaligned.
#
#
#
#
Example
#
#
#
#
#
#
#
# class A {...};
#
# void F ()
#
# {
#
# Const A *PA = new A;//const Object
#
# A *pb;//Non-const object
#
#
#
#
#//PB = PA; There will be an error, and you cannot assign a const object pointer to a non-const object
#
# PB = Const_cast<a*> (PA); It's OK now.
#
# ...
#
# }
#

# 4) reinterpret_cast<t*> (a)
#
# any pointer can be converted to another type of pointer, t must be a pointer, a reference, an arithmetic type, a pointer to a function, or a pointer to a class member.
#
# expression reinterpret_cast<t*> (a) can be used for conversions such as char* to int*, or one_class* to unrelated_class*, and therefore may not be secure.
#
#
#
#
Example
#
# class A {...};
#
# class B {...};
#
# void F ()
#
# {
#
# A * pa = new A;
#
# void* PV = reinterpret_cast<a*> (PA);
#
#//PV now points to an object of type B, which may be unsafe
#
#    ...
#
# }

Summarize all the cast functions in C + + (Const_cast,reinterpret_cast,static_cast,dynamic_cast)

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.