Summary of Explicit conversions such as C ++ reinterpret_cast and const_cast

Source: Internet
Author: User

 

Reinterpret_cast, const_cast, static_cast, and dynamic_cast Explicit conversions

Cpp Code
 

  1. # Include <iostream. h>
  2. Int main (void)
  3. {
  4. // Reinterpret_cast
  5. // Convert one type pointer to another type pointer, which does not modify the data storage format of pointer variable values during conversion
  6. // You only need to re-interpret the pointer type during compilation. It can convert the pointer to an integer but cannot be used for non-pointer conversion.
  7. Double D = 9.3;
  8. Double * Pd = & D;
  9. Int * Pi = reinterpret_cast <int *> (PD );
  10. Class {};
  11. Class B {};
  12. A * pA = new;
  13. B * pb = reinterpret_cast <B *> (PA); // convert Pa to B
  14. Long J = reinterpret_cast <long> (PA); // convert the pointer to an integer.
  15. // Int I = 9;
  16. // Double X = reinterpret_cast <double> (I); // reinterpret_cast cannot be used for non-pointer conversion.
  17. // Const_cast
  18. // 1. Remove the constant attribute of the pointer variable and convert it into a common variable corresponding to the pointer type,
  19. // 2. In turn, you can convert a constant pointer to a constant pointer variable.
  20. // 3. He cannot convert a non-pointer constant to a common variable.
  21. // Example: const I = 10;
  22. // Int j = const_cast <int> (I); // cannot be converted
  23. Const int ppp = 998;
  24. Const int * pca = & ppp;
  25. Int * p = const_cast <int *> (pca); // convert it to a common variable corresponding to the pointer type, removing const;
  26. Const A * paa = new;
  27. A * ppppa = const_cast <A *> (paa); // It is converted to A common variable corresponding to the pointer type, removing const;
  28. Int * pii = 0; // in turn, you can convert a constant pointer to a constant pointer variable.
  29. Const int * piiic = const_cast <const int *> (pii );
  30. //////////////////////////////////////// //////////////////////////////////////// //
  31. // Static_cast
  32. // It is used to convert between basic types and new classes with inheritance relationships
  33. // Static_cast is not used to convert pointer types. Its efficiency is not as efficient as reinterpret_cast.
  34. Int in = 99;
  35. Double dn = static_cast <double> (in); // used to convert between a basic type and a class with an inheritance relationship
  36. Class Base {};
  37. Class derv: public Base {};
  38. Derv dd;
  39. Base bbbb = static_cast <Base> (dd); // conversions between types with inheritance relationships
  40. // Static_cast is not used to convert pointer types. Its efficiency is not as efficient as reinterpret_cast.
  41. Base * PB1 = new base;
  42. Derv * PDER = static_cast <derv *> (PB1); // base class to inheritance class
  43. Derv * pder1 = new derv;
  44. Base * pbase1 = static_cast <base *> (pder1); // inherits class pointer to parent class pointer
  45. //////////////////////////////////////// //////////////////////////////////
  46. // Dynamic_cast
  47. // 1. type conversion can only be performed between pointers of inherited class objects or between references
  48. // 2. This kind of conversion is not at compilation, but dynamic at runtime.
  49. // 3. There is no inheritance relationship, but the converted class has the pointer of the virtual function object for conversion.
  50. Derv * dp = new derv;
  51. Base * bv = dynamic_cast <Base *> (dp); // type conversion between pointers inheriting class objects
  52. Derv dpp; // type conversion between inherited Class Object references
  53. Base & B = dynamic_cast <Base &> (dpp );
  54. Class AA {virtual fun (){}
  55. Virtual ~ AA (){}};
  56. Class BB {};
  57. // There is no inheritance relationship, but the converted class has the pointer of the virtual function object for conversion. Compilation can be done through
  58. AA * pAA = new AA;
  59. BB * pBB = dynamic_cast <BB *> (pAA );
  60. // There is no inheritance relationship, and the converted class does not have a pointer to the virtual function object for conversion. Compilation cannot pass
  61. BB * pBBB = new BB;
  62. AA * pAAA = dynamic_cast <AA *> (pBBB );
  63. Return 1;
  64. }
# Include <iostream. h> int main (void) {// reinterpret_cast // convert one type pointer to another type pointer, without changing the data storage format of pointer variable values during conversion // you only need to re-interpret the pointer type during compilation, it can convert a pointer to an integer but cannot be used to convert a non-pointer to a double D = 9.3; double * Pd = & D; int * Pi = reinterpret_cast <int *> (PD); Class A {}; Class B {}; A * pA = new; B * pb = reinterpret_cast <B *> (PA); // convert Pa to blong J = reinterpret_cast <long> (PA ); // convert the pointer to an integer // int I = 9; // Double X = reinterpret_cast <double> (I); // reinterpret_cast cannot be used for non-pointer conversion. Change // const_cast // 1. it is used to remove the common attribute of the pointer variable and convert it into a common variable corresponding to the pointer type. // 2. in turn, you can also convert a constant pointer to a constant pointer variable // 3. he cannot convert a non-pointer constant to a common variable // example: const I = 10; // Int J = const_cast <int> (I ); // const int PPP = 998; const int * PCA = & PPP; int * P = const_cast <int *> (PCA ); // convert it to a common variable corresponding to the pointer type, excluding const; const A * PAA = new A; A * ppppa = const_cast <A *> (PAA ); // It is converted to a common variable corresponding to the pointer type, excluding const; int * PII = 0; // In turn, you can also convert a constant pointer to a constant pointer variable const int * piiic = const_cas T <const int *> (PII ); //////////////////////////////////////// //////////////////////////////////////// //// static_cast // convert between the basic type and the class with an inheritance relationship // static_cast is not used for conversion between the pointer type, its efficiency is not as efficient as reinterpret_cast; int in = 99; double DN = static_cast <double> (in ); // convert class base {}; class derv: public base {}; derv dd; base BBBB = static_cast <base> (dd); // conversions between types with inheritance relationships // static_cast is not used for conversions between pointer types, and its efficiency is not reinterpre T_cast is highly efficient. Base * PB1 = new base; derv * PDER = static_cast <derv *> (PB1); // The base class is converted to the inheritance class derv * pder1 = new derv; base * pbase1 = static_cast <base *> (pder1 ); // convert the inherited class pointer to the parent class pointer /////////////////////////////// //////////////////////////////////////// //// dynamic_cast // 1. type conversion can only be performed between pointers of inherited class objects or between references // 2. this type of conversion is dynamic at runtime rather than during compilation. there is no inheritance relationship, but the converted class has the pointer of the virtual function object to convert derv * dp = new derv; base * bv = dynamic_cast <base *> (DP ); // type conversion between pointers of inherited class objects derv DPP; // inheritance class Type conversion between object references base & B = dynamic_cast <base &> (DPP); Class AA {virtual fun () {} virtual ~ AA () {}; Class BB {}; // There is no inheritance relationship, but the converted class has the pointer of the virtual function object for conversion, compilation can be performed through aa * PAA = new AA; bb * PBB = dynamic_cast <BB *> (PAA); // There is no inheritance relationship, the converted class does not have a pointer to a virtual function object for conversion. Compilation cannot be performed using BB * Pbbb = new BB; AA * paaa = dynamic_cast <AA *> (Pbbb ); return 1 ;}

Summary:

  • Reinterpret_cast converts a type pointer to another type pointer.
  • Const_cast is used to remove the constant attribute of the pointer variable and convert it to a common variable corresponding to the pointer type. In turn, it can also convert a constant pointer to a constant pointer variable.
  • Static_cast is used to convert between basic types and classes with inheritance relationships. It is not used to convert between pointer types.
  • Dynamic_cast can only convert data types between pointers of inherited class objects or between references.

The above only converts dynamic_cast, which are dynamic at runtime rather than during compilation. Others are compiled

--------------------------------------

Type Conversion characters of Standard C ++: static_cast, dynamic_cast, reinterpret_cast, and const_cast.

Static_cast
Usage: static_cast <type-id> (exdivssion)
This operator converts exdivssion to the type-id type, but there is no runtime type check to ensure the conversion security. It has the following usage:
① It is used to convert pointers or references between classes and subclasses in the class hierarchy.
It is safe to perform upstream conversion (converting the pointer or reference of a subclass to a base class;
When performing a downstream conversion (converting a base class pointer or reference to a subclass), it is not safe because there is no dynamic type check.
② It is used for conversion between basic data types. For example, convert int to char and convert int to enum. The security of such conversions must also be ensured by developers.
③ Convert a null pointer to a null pointer of the target type.
④ Convert any type of expression to void type.

Note: static_cast cannot convert the const, volitale, or _ unaligned attributes of exdivssion.

Dynamic_cast
Usage: dynamic_cast <type-ID> (exdivssion)
This operator converts exdivssion to an object of the Type-ID type. Type-ID must be a class pointer, class reference, or void *;
If type-ID is a class pointer type, exdivssion must also be a pointer. If type-ID is a reference, exdivssion must also be a reference.

Dynamic_cast is mainly used for upstream and downstream conversions between classes, and can also be used for cross conversions between classes.
When performing upstream conversion between classes,

Dynamic_cast and static_cast have the same effect;
Dynamic_cast provides the type check function for downstream conversions, which is safer than static_cast. CPP Code
 

  1. Class B {
  2. Public:
  3. Int m_iNum;
  4. Virtual void foo ();
  5. };
  6. Class D: public B {
  7. Public:
  8. Char * m_szName [100];
  9. };
  10. Void func (B * pb ){
  11. D * pd1 = static_cast <D *> (pb );
  12. D * pd2 = dynamic_cast <D *> (pb );
  13. }
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 above Code segment, if PB points to a D-type object, pd1 and Pd2 are the same, and it is safe to execute D-type operations on these two pointers;
However, if PB points to a B-type object, pd1 will be a pointer to this object, it is not safe to perform operations of the D type (for example, to access m_szname ),
Pd2 is a null pointer.

Note: B must have virtual functions; otherwise, compilation errors may occur. static_cast does not have this restriction.
This is because the runtime type check requires runtime type information, which is stored in the virtual function table of the class (
For more information about the concept of virtual function tables, see). Only classes that define virtual functions have virtual function tables,
Classes that do not define virtual functions do not have virtual function tables.

In addition, dynamic_cast also supports cross cast ). The following code is used. CPP Code
 

  1. Class {
  2. Public:
  3. Int m_iNum;
  4. Virtual void f (){}
  5. };
  6. Class B: public {
  7. };
  8. Class D: public {
  9. };
  10. Void foo (){
  11. B * pb = new B;
  12. Pb-> m_iNum = 100;
  13. D * pd1 = static_cast <D *> (pb); // compile error
  14. D * pd2 = dynamic_cast <D *> (pb); // pd2 is NULL
  15. Delete pb;
  16. }
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 errord * Pd2 = dynamic_cast <D *> (PB); // Pd2 is nulldelete Pb ;}

In function Foo, using static_cast for conversion is not allowed,

An error occurs during compilation. The conversion using dynamic_cast is allowed and the result is a null pointer.

Reinterpret_cast
Usage: reinterpret_cast <type-ID> (exdivssion)
Type-ID must be a pointer, reference, arithmetic type, function pointer, or member pointer.
It can convert a pointer to an integer, or an integer to a pointer (first, convert a pointer to an integer,
You can also obtain the original pointer value after converting the integer to the original type ).

This operator is used in many ways.

Const_cast
Usage: const_cast <type-ID> (exdivssion)
This operator is used to modify the const or volatile attributes of the type. Apart from the const or volatile modifier, The type_id and exdivssion types are the same.
Constant pointers are converted to non-constant pointers and still point to the original object;
Constant reference is converted to a non-constant reference and still points to the original object. Constant object is converted to a non-constant object.

Voiatile and const classes. The following is an example of Cpp Code.
 

  1. Class B {
  2. Public:
  3. Int m_iNum;
  4. }
  5. Void foo (){
  6. Const B b1;
  7. B1.m _ iNum = 100; // comile error
  8. B b2 = const_cast <B> (b1 );
  9. B2. m_iNum = 200; // fine
  10. }
Class B {public: int m_iNum;} void foo () {const B b1; b1.m _ iNum = 100; // comile errorB b2 = const_cast <B> (b1 ); b2. m_iNum = 200; // fine}

The above code will report an error during compilation, because b1 is a constant object and cannot be changed;
Using const_cast to convert it into a constant object, you can change its data members at will. Note: b1 and b2 are two different objects.

 

 

 

Address: http://kooyee.iteye.com/blog/364632

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.