C ++ standard conversion operator reinterpret_cast

Source: Internet
Author: User
Tags type casting
Reinterpret_cast <new_type> (expression)

The reinterpret_cast operator is used to process conversions between irrelevant types. It generates a new value, which has exactly the same bit as the original parameter (expressoin.

What is an irrelevant type? I have not figured out, but I have not found a good document to illustrate the relationships between types (except class inheritance ). The last half of the sentence shows the literal meaning of reinterpret_cast: re-interpretation (type bit ). Can we give bitwise of A type value to another type as its value at will? Actually not.

The ibm c ++ Guide clearly tells us where reinterpret_cast can be used as a conversion OPERATOR:

    • From pointer type to an integer type that is large enough
    • From Integer type or enumeration type to pointer type
    • From a pointer to a function to another pointer to a function of different types
    • From a pointer to an object to another pointer to an object of Different Types
    • From a pointer to a class function member to another pointer to a different type of function Member
    • From a pointer to a class data member to another pointer to a different type of data member

However, I tested it in xcode. In fact, the use of reinterpret_cast is not limited to the items mentioned above. pointers of any type can be converted to each other without compilation errors. The items listed above may be restrictions on the use of reinterpret_cast in Linux, or the reinterpret_cast method recommended by IBM.

So to sum up, reinterpret_cast is used to convert any pointer (or reference) type, and between the pointer and the integer type that is large enough; from the integer type (including the enumeration type) to the pointer type, regardless of the size.

(The so-called "Integer type large enough" depends on the operating system parameters. If it is a 32-bit operating system, it must be INTEGER (INT) or above; A 64-bit operating system requires at least a long integer ). The specific size can be viewed using the sizeof operator ).

What is the function of reinterpret_cast?

From the above introduction to reinterpret_cast, we can feel that reinterpret_cast is a very powerful operator, becauseIt can ignore racial isolation and.However, just like the biological principles, random hybridization that do not conform to the natural laws will only produce a species that cannot survive for a long time. Use reinterpret_cast between different types.ProgramAnd cannot be used..

For exampleCode

Typedef Int(* Functionpointer )(Int);

IntValue = 21;

Functionpointer funcp;

Funcp =Reinterpret_cast<Functionpointer> (& value );

Funcp (value );

I first use typedef to define a pointer type pointing to a function. The function to which it points accepts an int type as a parameter. Then I used reinterpret_cast to convert an integer address to this function type and assign the value to the corresponding variable. Finally, I used this integer variable as a parameter and handed it to the pointer variable pointing to the function.

This process is successfully compiled by the compiler, but once it is run, we will getAn error occurred while running "exc_bad_access ".Because what we find through the address indicated by funcp is not the Function entry.

It can be seen that although reinterpret_cast seems powerful, it does not play a very wide role. IBM's c ++ guide, the FAQ page of Bjarne stroustrup, the father of C ++, and the visual C ++ of msdn also pointed out:Incorrect use of reinterpret_cast can easily lead to program insecurity. The reinterpret_cast method is correct only when the converted type value is converted back to its original type.

In this way, the purpose of converting reinterpret_cast to another type is to temporarily hide your own (Be an undercover?If you really want to use that value, you still need to show its true face. So what value does it have in C ++?

The Visual C ++ Developer Center of msdn provides the following values:Used to assist in Hash Functions. The following is an example of msndn:

                 // Expre_reinterpret_cast_operator.cpp  // Compile with:/ESCs  # Include < Iostream > // Returns a hash code based on an address  Unsigned   Short Hash ( Void * P ){ Unsigned   Int Val = Reinterpret_cast < Unsigned   Int > (P ); Return ( Unsigned Short) (Val ^ (Val> 16 ));} Using   Namespace  STD ; Int Main (){ Int A [20]; For ( Int I = 0; I <20; I ++) Cout <Hash (a + I) < Endl ;} // If it is a 64-bit system like me, you may needUnsignedIntUnsignedLong to run.             

This code is suitable for reflecting the concept of hash. We will not go into it for the time being, but at least look at the operations in the hash function. We can also see that the operation on integers is obviously more convenient for address operations. Storing integer values in a collection is more scalable than the storage address (of course, if the storage void * is also highly scalable ), the only possible loss is the integer and address conversion during access (which is negligible ).

But the readability may not be high, so in this case, you can useTypedefTo define the pointer type:
Typedef Unsigned IntPointertype;

This is not even better. When we run it on a 64-bit machine, we only need to change it:

Typedef Unsigned LongPointertype;

When reinterpret_cast faces const

The ibm c ++ guide points out:Reinterpret_cast cannot remove the const modifier like const_cast.
What does this mean? The Code is the most intuitive expression:

IntMain (){Typedef Void(* Functionpointer) (INT );IntValue = 21;Const Int* Pointer = & value;//Int* Pointer_r =Reinterpret_cast<Int*> (Pointer );// Error:Reinterpret_castFrom type'Const Int* 'To type'Int* 'Casts away constnessFunctionpointer funcp =Reinterpret_cast<Functionpointer> (pointer );}

In this example, we want to convert the pointer to const into a non-const pointer, as shown in the previous example of const_cast. However, when reinterpret_cast is used, the compiler directly reports an error to organize the process. This reflects the uniqueness of const_cast.

However, another conversion in the example is to pay the pointer pointing to the const int to the pointer pointing to the function. The compilation is successful and the result is meaningless, as shown in the preceding example.

From another perspective, this seems reasonable. Because

Const Int* P = & value;
Int*ConstQ = & value;

The two statements have different meanings. The former is"Immutable content", The latter is"The address to which the IP address is directed is unchangeable."(For details, refer to here ). Therefore, the pointer to the function should have the "immutable content" feature by default.

After all, the operation process of a function is fixed after compilation. The only thing we can do is to pass some parameters to the pointer without changing the process of the compiled function. From this perspective, it is reasonable to use reinterpret_cast to convert from const int * To functionpointer in the above example, because it does not remove the const limitation.

Director: Jim Fawcett
    1. C ++ language tutorial-type casting
    2. Object Oriented Design
    3. IBM complilers-xl c/C ++ v9.0 for Linux-The reinterpret_cast operator (C ++ only)
    4. Bjarne stroustrup's c ++ style and technique FAQ
    5. msdn visual c ++ Developer Center-reinterpret_cast operator

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.