reinterpret_cast or static_cast ?



 DEVELOP > c-Plus-Plus > reinterpret_cast or static_cast ?

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Lucy Ludmiller"
Date: 02 Sep 2006 08:13:53 PM
Object: reinterpret_cast or static_cast ?
I have two classes:
class base { ... };
and
class derived : public base { ... };
I have a function :
void foo(const base*) { ... }
I want to be able to cast back to derived (I only have a ptr to base in
this compilation unit), and then invoke a method on object derived
- do I use a static_cast or reinterpret_cast to cast "upward" ?
- any reason why one is a better choice than the other ?
.

User: "Alf P. Steinbach"

Title: Re: reinterpret_cast or static_cast ? 02 Sep 2006 08:21:20 PM
* Lucy Ludmiller:

I have two classes:

class base { ... };

and

class derived : public base { ... };


I have a function :

void foo(const base*) { ... }

If a nullvalue for the pointer is not meaningful, make that
void foo( base const& )

I want to be able to cast back to derived (I only have a ptr to base in
this compilation unit), and then invoke a method on object derived

Then make that
void foo( derived const& )

- do I use a static_cast or reinterpret_cast to cast "upward" ?

static_cast or dynamic_cast.
If base has one or more virtual member functions, make that
dynamic_cast. Choose casting of reference for exception, or casting of
pointer + assert for assertion. Be sure to test that piece of code
extremely thoroughly.
Or (much!) better, design the cast away.

- any reason why one is a better choice than the other ?

They're different. Conceptually a reinterpret_cast reinterprets the
bits of the pointer value as some other pointer type, without doing
necessary adjustments. In this context reinterpret_cast yields
undefined behavior.
Generally (there is one exception) you can only use the result of a
reinterpret_cast in a portable way by casting back to the original type.
For someone who is unsure of casting, reinterpret_cast means you have a
bug, and any cast whatsoever means you have a potential set of bugs.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
.
User: "dasjotre"

Title: Re: reinterpret_cast or static_cast ? 07 Sep 2006 05:29:37 AM
Alf P. Steinbach wrote:

If base has one or more virtual member functions, make that
dynamic_cast. Choose casting of reference for exception, or casting of
pointer + assert for assertion. Be sure to test that piece of code
extremely thoroughly.

or boost::polymorphic_downcast
.



  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER