Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > reinterpret_cast<>() v. static_cast<>()

Reply
Thread Tools

reinterpret_cast<>() v. static_cast<>()

 
 
Ron Natalie
Guest
Posts: n/a
 
      01-19-2004

"Old Wolf" <(E-Mail Removed)> wrote in message news:(E-Mail Removed) om...
> I had previously assumed that this was a safe technique because
> the dynamic_cast would throw. But if this is not the case, then
> there is UB because of the 0-dereference (it might not even
> throw an exception at all).


Correct.

 
Reply With Quote
 
 
 
 
Nick Hounsome
Guest
Posts: n/a
 
      01-20-2004

"Old Wolf" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) om...
> > > dynamic_cast is a "safe" way to cast a base class to a derived class,
> > > but it requires you to include type information in your build. if at
> > > runtime, if the cast can't be performed, then the cast returns 0,
> > > otherwise the cast succeeds and you continue your program.

> >
> > That's how it works for pointers. For references, dynamic_cast succeeds
> > or throws and exception.

>
> Is this UB:
> class Base { /* ... */ };
> class Derived: public Base { public: int bar; };
>
> void foo(Base *b)
> {
> try {
> dynamic_cast<Derived *>(b)->bar = 3;
> }
> catch(...) {
> do_error("non-derived object passed");
> }
> }
>
> I had previously assumed that this was a safe technique because
> the dynamic_cast would throw. But if this is not the case, then
> there is UB because of the 0-dereference (it might not even
> throw an exception at all).


It can never throw an exception (except in the sense that theoretically it
could
because deref. 0 is UB).

You want:

dynamic_cast<Derived&>(*b).bar = 3;

or replace the whole thing with:

if( Dervived* dp = dynamic_cast<Derived*>(b))
{
dp->bar = 3;
}
else
do_error(.....);

P.S. unless you add one or more virtual methods
to Base dynamic_cast will
not work for you anyway - it will just do the same as
static_cast which will NEVER return null (unless b is).


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments