Explanation of four forced conversions of C ++

Source: Internet
Author: User

What is type conversion?
The meaning of type 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.

Type conversion between C and C ++
[Cpp]
// C:
// Copy the Code as follows:
(T) element or T (element)
 
// C ++:
// Copy the Code as follows:
Reinterpret_cast <T *> (expression)
Dynamic_cast <T *> (expression)
Static_cast <T *> (expression)
Const_cast <T *> (expression)

// C:
// Copy the Code as follows:
(T) element or T (element)

// C ++:
// Copy the Code as follows:
Reinterpret_cast <T *> (expression)
Dynamic_cast <T *> (expression)
Static_cast <T *> (expression)
Const_cast <T *> (expression) Four forced transformations of C ++, each of which is suitable for specific purposes:
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 this), and it is closest to the C-style conversion.

Const_cast is generally used to force the elimination of object constants. 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.

General explanation:
Dynamic_cast // usually used for conversion between the base class and the derived class

Static_cast // General conversion. If you do not know which one to use, use this

Const_cast // converts const and volatile.

Reinterpret_cast // is used to convert a character pointer to an integer without any association.

Specific analysis:
1) static_cast <T *> (a) compiler processing during compilation

Converts address a to type T. T and a must be pointer, reference, arithmetic, or enumeration.

Expression static_cast <T *> (a). The value of a is converted to the type T specified in the template.

During the conversion process at runtime, no type check is performed to ensure the security of the conversion.

Static_cast can convert each other between built-in data types. classes can only convert between correlated pointer types. Pointers can be converted in the inheritance system, but cannot be converted into a type other than the inheritance system.

Copy the Code as follows:
[Cpp]
Class {...};
Class B {...};
Class D: public B {...};
Void f (B * pb, D * pd)
{
D * pd2 = static_cast <D *> (pb); // insecure. pb may be a pointer to B.
B * PBS = static_cast <B *> (pd); // safe
A * pa2 = static_cast <A *> (pb); // error A has no inheritance relationship with B
...
}

Class {...};
Class B {...};
Class D: public B {...};
Void f (B * pb, D * pd)
{
D * pd2 = static_cast <D *> (pb); // insecure. pb may be a pointer to B.
B * PBS = static_cast <B *> (pd); // safe
A * pa2 = static_cast <A *> (pb); // error A has no inheritance relationship with B
...
} 2) at runtime, dynamic_cast <T *> (a) checks whether the conversion is possible.

Completes the upgrade of the class hierarchy. T must be a pointer, reference, or non-type pointer. A must be a pointer or referenced expression.

Dynamic_cast can only be applied to pointers or references. It does not support built-in data types.

Expression dynamic_cast <T *> (a) converts a value to an object pointer of type T. If type T is not a base type of a, this operation returns a null pointer.

Unlike static_cast, it checks whether the two pointers before and after conversion belong to the same inheritance tree. It also checks the actual type of the object referenced by the pointer to determine whether the conversion is feasible.

If possible, it returns a new pointer and even calculates the necessary offset for processing multi-inheritance. If the two pointers cannot be converted, the conversion fails, and a NULL pointer is returned ).

Obviously, to make dynamic_cast work normally, the compiler must support the runtime type information (RTTI ).

Copy the Code as follows:
[Cpp]
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'

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' 3) const_cast <T *> (a) compiler processing during compilation

Remove constants from the type. Except for const or the number of unstable addresses, T and a must be of the same type.

The const_cast <T *> (a) expression is used to remove the following attributes from a class: const, volatile, and _ unaligned.

For the const type defined in itself, even if you remove the const type, you must be careful when operating this piece of content, only r can not w operation, otherwise there will still be errors

The const_cast operation cannot be converted between different types. It only converts an expression to a constant. It can convert a data that is not of the const type to the const type, or remove the const attribute.

Copy the Code as follows:
[Cpp]
Class {...};
Void f ()
{
Const A * pa = new A; // const object
A * pb; // non-const object
// Pb = pa; // an error occurs. You cannot assign a const object pointer to a non-const object.
Pb = const_cast <A *> (pa); // now OK
...
}
 
Const char * p = "123 ";
Char * c = const_cast <char *> (p );
C [0] = 1; // on the surface, const is removed by compilation, but the system still does not allow this operation when operating its address.

Class {...};
Void f ()
{
Const A * pa = new A; // const object
A * pb; // non-const object
// Pb = pa; // an error occurs. You cannot assign a const object pointer to a non-const object.
Pb = const_cast <A *> (pa); // now OK
...
}

Const char * p = "123 ";
Char * c = const_cast <char *> (p );
C [0] = 1; // on the surface, const is removed by compilation, but the system still does not allow this operation when operating its address. 4) reinterpret_cast <T *> (a) compiler processing during compilation

Any pointer can be converted to another type of pointer. T must be a pointer, reference, arithmetic type, pointer to a function, or pointer to a class member.

The reinterpret_cast <T *> (a) expression can be used for conversion from char * to int *, or from One_class * To Unrelated_class *, which may be insecure.

Copy the Code as follows:
[Cpp]
Class {...};
Class B {...};
Void f ()
{
A * pa = new;
Void * pv = reinterpret_cast <A *> (pa );
// Pv now points to an object of type B, which may be insecure
...
}

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.