C ++ four cast Operators

Source: Internet
Author: User

 

The forced transformation of C-style is as follows:

(T) expression or

T (expression) // function-style)

There is no essential difference between the two forms.

C
Style transformation works well. However, such conversion characters can also be applied to Class and Class pointers indiscriminately. The ANSI-C ++ standard defines four new delimiters: reinterpret_cast, static_cast, dynamic_cast, and const_cast to control the type conversion between classes.

1.1 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 into an integer or an integer into a pointer.

This operator can be converted between unrelated types. The operation result is simply a binary copy of the value from a pointer to another pointer. Do not check or convert any types of content that points between types. Reinpreter_cast is specially used for underlying forced transformation, resulting in implementation of dependencies (that is, cannot be transplanted.

Int n = 9;

// Reinterpret_cast only copies N bits to D, so D contains useless values.

Double D = reinterpret_cast <double &> (N );

1.2 const_cast

Usage: const_cast <type_id> (expression)

Used to modify the const or volatile attributes of the type. In addition to const or volatile modification, type_id and expression are of the same type and are generally used to forcibly remove the object's constants. It is the only forced transformation of the C ++ style that can achieve this, and C does not provide a mechanism to eliminate const (verified ).

Constant pointers are converted to non-constant pointers and still point to the original objects. Constant references are converted to non-constant references and still point to the original objects; constant objects are converted to very large objects.

1.3 static_cast

Usage: static_cast <type-ID> (expression)

This operator converts expression to the Type-ID type, but does not check the runtime type to ensure the conversion security. It allows arbitrary implicit conversions and reverse conversions. It has the following usage:

1) it is used for conversion between basic data types. For example, if int is converted to Char, the non-const object is converted to a const object (this is not the opposite direction, and C ++ only supports const_cast ).

2) convert a null pointer to a pointer of the target type. (The previous method was to use forced conversion (Type-ID *))

3) convert any type of expression to void type.

4) applies to the class pointer, which allows the pointer of the subclass type to be converted to the pointer of the parent class (upercasting is a valid implicit conversion); can also execute the opposite action, that is, the conversion parent class is its sub-class (downcasting). The security of this conversion needs to be ensured by developers (mainly in non-upstream and downstream transformation ).

Class base {};

Class derived: public base {};

Base * A = new base;

Derived * B = NULL;

B = static_cast <derived *> (a); // It can be compiled, but there are security risks (such as access to the/derived member)

Note:

1. static_cast cannot convert the const, volitale, or _ unaligned attribute of expression.

2. in non-basic type or up/down transformation, the parent class to be converted needs to check whether it is consistent with the target type. Otherwise, if the conversion is performed between two completely unrelated classes, this will cause compilation errors.

1.4 dynamic_cast

It is only used for pointer and reference of objects and is mainly used for executing "secure downward transformation". That is to say, it is necessary 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.

When used for polymorphism (including virtual functions), it allows any implicit type conversion and the opposite process. However, unlike static_cast, in the latter case (that is, the opposite process of implicit conversion), dynamic_cast checks whether the operation is effective based on the rtti information. That is, dynamic_cast will check whether the conversion can return a valid and complete object to be requested. This check is not a syntax check, but a real situation check. During running, if the converted pointer is not a valid and complete object pointer requested, the return value is null.

First, let's look at the rtti-related part. Generally, many compilers find the rtti information of an object through vtable, which means that if the base class has no virtual function, therefore, the real type of the object referred to by a base class pointer variable cannot be determined. At this time, dynamic_cast can only be used for secure conversion (upercasting), for example, converting a pointer from a derived class to a base class pointer, dynamic_cast is not required for this conversion.

Class base {virtual dummy (){}};

Class derived: public base {};

Class other {};

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 type conversion is performed for a reference type and this conversion is not possible, an // bad_cast exception type will be thrown during the runtime:

Derived D3 = dynamic_cast <derived &> (* B1); // succeeds

Derived D4 = dynamic_cast <derived &> (* B2); // fails: exception thrown

Note: The base must have virtual functions; otherwise, compilation errors may occur.

Conclusion 1.5

The four types of conversion operators are not necessary for implicit type conversion.

Static_cast can complete ing in a wider range. This unrestricted ing is accompanied by insecurity. When performing upstream conversion between classes, dynamic_cast and static_cast have the same effect. When performing downstream conversion (the base class must contain virtual functions), dynamic_cast has the type check function, it sacrifices efficiency, but is safer than static_cast.

The forced transformation of C-style is as follows:

(T) expression or

T (expression) // function-style)

There is no essential difference between the two forms.

C
Style transformation works well. However, such conversion characters can also be applied to Class and Class pointers indiscriminately. The ANSI-C ++ standard defines four new delimiters: reinterpret_cast, static_cast, dynamic_cast, and const_cast to control the type conversion between classes.

1.1 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 into an integer or an integer into a pointer.

This operator can be converted between unrelated types. The operation result is simply a binary copy of the value from a pointer to another pointer. Do not check or convert any types of content that points between types. Reinpreter_cast is specially used for underlying forced transformation, resulting in implementation of dependencies (that is, cannot be transplanted.

Int n = 9;

// Reinterpret_cast only copies N bits to D, so D contains useless values.

Double D = reinterpret_cast <double &> (N );

1.2 const_cast

Usage: const_cast <type_id> (expression)

Used to modify the const or volatile attributes of the type. In addition to const or volatile modification, type_id and expression are of the same type and are generally used to forcibly remove the object's constants. It is the only forced transformation of the C ++ style that can achieve this, and C does not provide a mechanism to eliminate const (verified ).

Constant pointers are converted to non-constant pointers and still point to the original objects. Constant references are converted to non-constant references and still point to the original objects; constant objects are converted to very large objects.

1.3 static_cast

Usage: static_cast <type-ID> (expression)

This operator converts expression to the Type-ID type, but does not check the runtime type to ensure the conversion security. It allows arbitrary implicit conversions and reverse conversions. It has the following usage:

1) it is used for conversion between basic data types. For example, if int is converted to Char, the non-const object is converted to a const object (this is not the opposite direction, and C ++ only supports const_cast ).

2) convert a null pointer to a pointer of the target type. (The previous method was to use forced conversion (Type-ID *))

3) convert any type of expression to void type.

4) applies to the class pointer, which allows the pointer of the subclass type to be converted to the pointer of the parent class (upercasting is a valid implicit conversion); can also execute the opposite action, that is, the conversion parent class is its sub-class (downcasting). The security of this conversion needs to be ensured by developers (mainly in non-upstream and downstream transformation ).

Class base {};

Class derived: public base {};

Base * A = new base;

Derived * B = NULL;

B = static_cast <derived *> (a); // It can be compiled, but there are security risks (such as access to the/derived member)

Note:

1. static_cast cannot convert the const, volitale, or _ unaligned attribute of expression.

2. in non-basic type or up/down transformation, the parent class to be converted needs to check whether it is consistent with the target type. Otherwise, if the conversion is performed between two completely unrelated classes, this will cause compilation errors.

1.4 dynamic_cast

It is only used for pointer and reference of objects and is mainly used for executing "secure downward transformation". That is to say, it is necessary 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.

When used for polymorphism (including virtual functions), it allows any implicit type conversion and the opposite process. However, unlike static_cast, in the latter case (that is, the opposite process of implicit conversion), dynamic_cast checks whether the operation is effective based on the rtti information. That is, dynamic_cast will check whether the conversion can return a valid and complete object to be requested. This check is not a syntax check, but a real situation check. During running, if the converted pointer is not a valid and complete object pointer requested, the return value is null.

First, let's look at the rtti-related part. Generally, many compilers find the rtti information of an object through vtable, which means that if the base class has no virtual function, therefore, the real type of the object referred to by a base class pointer variable cannot be determined. At this time, dynamic_cast can only be used for secure conversion (upercasting), for example, converting a pointer from a derived class to a base class pointer, dynamic_cast is not required for this conversion.

Class base {virtual dummy (){}};

Class derived: public base {};

Class other {};

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 type conversion is performed for a reference type and this conversion is not possible, an // bad_cast exception type will be thrown during the runtime:

Derived D3 = dynamic_cast <derived &> (* B1); // succeeds

Derived D4 = dynamic_cast <derived &> (* B2); // fails: exception thrown

Note: The base must have virtual functions; otherwise, compilation errors may occur.

Conclusion 1.5

The four types of conversion operators are not necessary for implicit type conversion.

Static_cast can complete ing in a wider range. This unrestricted ing is accompanied by insecurity. When performing upstream conversion between classes, dynamic_cast and static_cast have the same effect. When performing downstream conversion (the base class must contain virtual functions), dynamic_cast has the type check function, it sacrifices efficiency, but is safer than static_cast.

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.