Coercion type conversions for C + +

Source: Internet
Author: User
Q: What is C-style conversion? What are static_cast, dynamic_cast and reinterpret_cast? What's the difference? Why should you pay attention?


A: The meaning of the conversion is to change the representation of a variable by changing its type to another type. To convert a simple object for a type to another object you would use the traditional type conversion operator.


For example, to convert a pointer of a floating-point number of type doubole to an integral type:

Code

int i;double d;i = (int) d;


Or:

i = int (d);


Works well for simple types that have standard definition transformations. However, such a translator can also be applied to classes (class) and class pointers without indiscriminate. The ansi-c++ standard defines four new conversions: ' Reinterpret_cast ', ' static_cast ', ' dynamic_cast ' and ' const_cast ', to control the type conversion between classes (Class).


Code:

reinterpret_cast<new_type> (expression) dynamic_cast<new_type> (expression) static_cast<new_type > (expression) const_cast<new_type> (expression)


1 reinterpret_cast


Reinterpret_cast converts a pointer to a pointer of another type. It also allows conversion from one pointer to an integer type. Vice versa. Is the pointer specific address value as an integer value? )


This operator can be converted between non-related types. The result of the operation is simply a binary copy of the value from one pointer to another pointer. Content that is pointed to between types does not have any type of check and conversion. If the case is a copy from a pointer to an integral type, the interpretation of the content is system-dependent, so any implementation is not convenient. A pointer that is converted to an integer large enough to contain it can be converted back to a valid pointer.


Code:

Class A {};class B {}; A * a = new A; b * b = reinterpret_cast<b *> (a);


Reinterpret_cast treats all pointer type conversions as if they were a traditional type conversion.


2 static_cast


Static_cast allows arbitrary implicit conversions and inverse conversion actions to be performed. (even if it is not allowed implicitly)


This means that it allows a pointer of the subclass type to be converted to a pointer of the parent class type (this is a valid implicit conversion), and can also perform the opposite action: transform the parent class to its subclass. In this final example, the converted parent class is not checked for consistency with the destination type.


Code:

Class Base {};class derived:public base {}; Base *a = new base;derived *b = static_cast<derived *> (a);


Static_cast, in addition to manipulating type pointers, can be used to perform explicit conversions of type definitions, as well as standard conversions between the underlying types:


Code:

Double D = 3.14159265;int i = static_cast<int> (d);


3 dynamic_cast


Dynamic_cast is used only for pointers and references to objects. When used with polymorphic types, it allows arbitrary implicit type conversions and the reverse process. However, unlike static_cast, in the latter case (note: The reverse process of implicit conversion), dynamic_cast checks whether the operation is valid. That is, it checks whether the transformation returns a valid full object that is requested.


The detection occurs at run time. If the pointer being converted is not a valid full object pointer being requested, the return value is null.


Code:

Class Base {virtual dummy () {}};class derived:public Base {}; base* B1 = new Derived; base* b2 = new Base; derived* D1 = dynamic_cast<derived *> (B1); succeedsderived* D2 = dynamic_cast<derived *> (b2); Fails:returns ' NULL '


If a reference type performs a type conversion and this conversion is not possible, an Bad_cast exception type is thrown:


Code:

Class Base {virtual dummy () {}};class derived:public Base {}; base* B1 = new Derived; base* b2 = new Base; Derived D1 = dynamic_cast<derived &*> (B1); succeedsderived D2 = dynamic_cast<derived &*> (b2); Fails:exception thrown

4 const_cast


This conversion type manipulates the Const property of the passed object, or is either set or removed:


Code:

Class C {};const c *a = new C; C *b = Const_cast<c *> (a);


The other three types of operators cannot modify the constant nature of an object. Note: ' Const_cast ' can also change a type of volatile qualifier.


Four forms of forced transformation in C + + each for a specific purpose


Dynamic_cast is primarily used to perform "safe downcasting", that is, to determine whether an object is a specific type in an inheritance system. It is the only forced transformation that cannot be performed with the old style syntax, and it is the only forced transformation that can have significant runtime costs.

Static_cast can be used to force implicit conversions (for example, a Non-const object to a const object, an int to a double, and so on), and it can also be used for a number of reverse transformations of such conversions (for example, the void* pointer is transformed into a typed pointer, The base class pointer is transformed to a derived class pointer), but it cannot transform a const object into a Non-const object (only const_cast can), which is closest to the C-style conversion.

Const_cast is generally used to force the elimination of the constants of an object. It is the only one that can do this with the C + + style of coercion.

Reinterpret_cast is intended for the underlying forced transformation, resulting in the implementation of dependency (Implementation-dependent) (that is, non-portable) results, such as transforming a pointer into an integer. Such a forced transformation should be extremely rare outside of the underlying code.

Above is the content of C + + coercion type conversion, more related content please pay attention to topic.alibabacloud.com (www.php.cn)!

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