C + + coercion type conversion: dynamic_cast, Const_cast, static_cast, reinterpret_cast__c++

Source: Internet
Author: User
Tags arithmetic volatile

dynamic_cast: Typically used when converting between base classes and derived classes, Run-time cast
Const_cast: Mainly for the conversion of const and volatile.
Static_cast: General conversion, no run-time check. Usually, if you don't know which to use, use this.

Reinterpret_cast: For conversions that do not have any association between them, such as the conversion of a character pointer to an integer number.

1) static_cast<t*> (a)
compiler handles at compile time
converts address A to type t,t and a must be a pointer, reference, arithmetic type, or enumeration type.
Expression static_cast<t*> (a), the value of a is converted to the type T specified in the template. During runtime conversion, no type checking is performed to ensure the security of the conversion. The
static_cast that it can convert between built-in data types, and that classes can only be converted between linked pointer types. The pointer can be converted to and transformed in the inheritance system, but cannot be converted to a type outside the inheritance system
Class A {...};
class B {...};
Class D:public B {...};
void F (b* pb, d* pd)
{
    d* pd2 = static_cast<d*> (pb);      & nbsp; //unsafe, PB may just be a pointer to B
    b* pb2 = static_cast<b*> (PD);        //Safe
    * PA2 = static_cast<a*> (pb);        //Error A has no inheritance relationship with B
    ...
}

2) dynamic_cast<t*> (a)
checks whether this conversion is possible at run time. The
completes the promotion in the class hierarchy. T must be a pointer, reference, or a pointer of no type. A must be an expression that determines a pointer or reference.
Dynamic_cast can only be applied to pointers or references, the built-in data type
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.
It is not just like static_cast, checking whether the two pointers before and after the conversion belong to the same inheritance tree, but also checking the actual type of the object referenced by the pointer to determine whether the conversion is feasible.
If it can, it returns a new pointer and even calculates the necessary offset to handle the need for multiple inheritance. If the two pointers cannot be converted, the conversion fails, and a null pointer (NULL) is returned.
Obviously, in order for dynamic_cast to work, you must have the compiler support Run-time type information (RTTI).

3) const_cast<t*> (a)
compiler handles the
Remove constants from the type at compile time, except for const or unstable changes, T and a must be of the same type. The
Expression const_cast<t*> (a) is used to remove the following attributes from a class: const, volatile, and __unaligned.
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);//now OK
    ...
}
for a type that is const when defined by itself, even if you remove the const, be careful when you manipulate this piece of content, only R can not w operation, or it will error
Const char* p = "123";
char* C = const_cast<char*> (p);
C[0] = 1;  //surface is stripped of the const by compilation, but the system still does not allow it to operate its address. The
Const_cast operation cannot be converted between different kinds. Instead, it simply converts an expression that it acts into a constant. It can convert a data that is not a const type to a const type, or remove the const attribute.
Try not to use const_cast, if found to call their own function, unexpectedly used const_cast, then hurriedly stop, reconsider the design.

4) reinterpret_cast<t*> (a)
compiler processing at compile time
Any pointer can be converted to another type of pointer, t must be a pointer, reference, arithmetic type, a pointer to a function, or a pointer to a class member.
The expression reinterpret_cast<t*> (a) can be used for transformations such as char* to int*, or one_class* to unrelated_class*, and may therefore be unsafe.
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
...
}
There are few occasions to use reinterpret_cast, and only in very necessary cases are other types of casts not meeting the requirements.

== ===========================================
= = 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 types we map to are 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 mutually inverse;
Static_cast uses type information at compile time to perform the conversion, performing the necessary instrumentation (such as pointer-crossing calculations, type checking) in the transformation. The operands are relatively safe.
Reinterpret_cast, on the other hand, is a mandatory type converter in C + +, and the operator modifies the operand type, but merely interprets the bit model of the given object without a binary conversion.
Examples are as follows:
int n=9;
Double D=static_cast < double > (n);
In the example above, we convert a variable from int to double. The binary expressions of these types 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_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 the useless value. This is because the reinterpret_cast is simply copying n bits to D, without making the necessary analysis.
Therefore, you need to use reinterpret_cast carefully.

The most common use of reinterpret_casts is to convert between function pointer types.
For example, suppose you have an array of function pointers:
Typedefvoid (*funcptr) ();//funcptr is a pointer to a function that has no arguments and the return value type is void
Funcptrfuncptrarray[10];//funcptrarray is an array that can hold 10 funcptrs pointers.

Let's assume that you want (for some inexplicable reason) to put a pointer to the following function into the Funcptrarray array:
int dosomething ();

You don't have to go through type conversions, because the dosomething function has a wrong type for a funcptrarray array. The function return value in the Funcptrarray array is a void type, and the DoSomething function return value is of type int.

FUNCPTRARRAY[0] = &dosomething;//error. Type mismatch
Reinterpret_cast allows you to force compilers to look at them in your own way:
Funcptrarray[0] = reinterpret_cast<funcptr> (&dosomething);
The code that converts the function pointer is not portable (c + + does not guarantee that all function pointers are represented in the same way), and in some cases such conversions produce incorrect results

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.