Discuss static_cast and reinterpret_cast

Source: Internet
Author: User
Tags type casting

Discuss static_cast and reinterpret_cast

By Sam ng
Translator: knife man

Original article: What static_cast <> is actually doing

This article discusses static_cast <> and reinterpret_cast <>.

Introduction
Many programmers have learned C before learning C ++ and are used to C style (type) conversion. When writing C ++ (Program), sometimes we may be a bit fuzzy when using static_cast <> and reinterpret_cast <>. In this article, I will describe what static_cast <> actually does and indicate some situations that will cause errors.

Generic (generic types)

Float F = 12.3;
Float * pF = & F;
// Static cast <>
// Compiled successfully, n = 12
Int n = static_cast <int> (f );
// Error, pointing to the type is irrelevant (note: the pointer variable PF is of the float type and will be converted to the int type now)
// Int * Pn = static_cast <int *> (PF );
// Compilation successful
Void * Pv = static_cast <void *> (PF );
// Compiled successfully, but * pn2 is meaningless memory (rubbish)
Int * pn2 = static_cast <int *> (PV );
// Reinterpret_cast <>
// Error. The Compiler knows that you should call static_cast <>
// Int I = reinterpret_cast <int> (f );
// Compiled successfully, but * PN is actually meaningless memory, just like * pn2
Int * Pi = reinterpret_cast <int *> (PF );
In short, static_cast <> will try to convert, for example, float-to-integer, while reinterpret_cast <> simply changes the compiler's intention to reconsider that object as another type.

Pointer types)

Pointer conversion is a bit complicated. We will use the following class in the rest of this article:
Class cbasex
{
Public:
Int X;
Cbasex () {x = 10 ;}
Void Foo () {printf ("cbasex: Foo () x = % d/N", x );}
};
Class cbasey
{
Public:
Int y;
Int * py;
Cbasey () {Y = 20; py = & Y ;}
Void bar () {printf ("cbasey: bar () y = % d, * py = % d/N", Y, * Py );
}
};
Class cderived: Public cbasex, public cbasey
{
Public:
Int Z;
};
Case 1: conversions between two irrelevant classes

// Convert Between cbasex * And cbasey *
// Conversion between cbasex * And cbasey *
Cbasex * PX = new cbasex ();
// Error, types pointed to are unrelated
// Error. The type direction is irrelevant.
// Cbasey * py1 = static_cast <cbasey *> (PX );
// Compile OK, but py2 is not cbasex
// Compilation succeeded, but py2 is not cbasex
Cbasey * py2 = reinterpret_cast <cbasey *> (PX );
// System crash !!
// System crash !!
// Py2-> bar ();
As we have learned in the generic example, if you try to convert an object to another unrelated class static_cast <>, reinterpret_cast <> will always "cheat" the compiler: the object is the irrelevant class.

Case 2: Convert to related classes
1. cderived * Pd = new cderived ();
2. printf ("cderived * Pd = % x/N", (INT) PD );
3.
4. // static_cast <> cderived *-> cbasey *-> cderived *
// Compiled successfully, implicit static_cast <> Conversion
5. cbasey * py1 = Pd;
6. printf ("cbasey * py1 = % x/N", (INT) py1 );
// Compiled successfully. Now pd1 = Pd
7. cderived * pd1 = static_cast <cderived *> (py1 );
8. printf ("cderived * pd1 = % x/N", (INT) pd1 );
9.
10. // reinterpret_cast
// Compilation succeeded, but py2 is not cbasey *
11. cbasey * py2 = reinterpret_cast <cbasey *> (PD );
12. printf ("cbasey * py2 = % x/N", (INT) py2 );
13.
14. // unrelated static_cast <>
15. cbasey * py3 = new cbasey ();
16. printf ("cbasey * py3 = % x/N", (INT) py3 );
// Compiled successfully, although py3 is just a "new cbasey ()"
17. cderived * pd3 = static_cast <cderived *> (py3 );
18. printf ("cderived * pd3 = % x/N", (INT) pd3 );
---------------------- Output ---------------------------
Cderived * Pd = 392fb8
Cbasey * py1 = 392fbc
Cderived * pd1 = 392fb8
Cbasey * py2 = 392fb8
Cbasey * py3 = 390ff0
Cderived * pd3 = 390fec

Note: When you use implicit static_cast to convert cderived * To cbasey * (row 5th), the result is (pointing to) cderived * (pointer backward) the offset is 4 (bytes ). To know how static_cast <> actually works, we have to look at the memory layout of cderived.

Memory layout of cderived (memory layout)

As shown in the figure, the memory layout of cderived includes two objects, cbasex and cbasey. The Compiler also knows this. Therefore, when you convert cderived * To cbasey *, it adds 4 bytes to the pointer and 4 to the pointer when you convert cbasey * To cderived. However, you can do this even if it is not a cderived.
Of course, this problem occurs only when you perform multi-inheritance. There is no difference between static_cast <> and reinterpret_cast <> when you convert cderived to cbasex.

Case 3: forward and backward conversion between void *

Because any pointer can be converted to void *, and void * can be converted back to any pointer (for static_cast <> and reinterpret_cast <> conversion ), errors may occur if you are not careful.

Cderived * Pd = new cderived ();
Printf ("cderived * Pd = % x/N", (INT) PD );
Cbasey * py = Pd; // compiled successfully, Py = Pd + 4
Printf ("cbasey * py = % x/N", (INT) py );
Void * pv1 = py; // compiled successfully, pv1 = py
Printf ("Void * pv1 = % x/N", (INT) pv1 );
// Pd2 = py, but we expect Pd2 = Py-4
Cderived * Pd2 = static_cast <cderived *> (pv1 );
Printf ("cderived * Pd2 = % x/N", (INT) Pd2 );
// System crash
// Pd2-> bar ();
---------------------- Output ---------------------------
Cderived * Pd = 392fb8
Cbasey * py = 392fbc
Void * pv1 = 392fbc
Cderived * Pd2 = 392fbc

Once we have converted the pointer to void *, we cannot easily convert it back to the original class. In the preceding example, the only way to return cderived * from a void * is to convert it to cbasey * and then to cderived *.
However, if we are not sure whether it is cbasey * or cderived *, we have to use dynamic_cast <> or typeid [2].

Note:
1. dynamic_cast <>, on the other hand, it can prevent a generic cbasey * from being converted to cderived *.
2. dynamic_cast <> requires classes to become polymorphism, that is, including "virtual" functions, and therefore cannot be void *.
Refer:
1. [msdn] C ++ Language Reference -- Casting
2. nishant sivakumar, casting basics-use C ++ casts in your VC ++. net programs
3. Juan soulie, C ++ language Tutorial: Type Casting
 

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.