3

I'm working on some legacy code that has a few lines like this:

try
{
    object = dynamic_cast< Object* >( _object );
}

Where _object is already an Object* to begin with. There is a comment in the code about trying to avoid a crash if _object has been freed. My question is, how does this work, if it does? Does dynamic_cast still do something if the start and end types are the same?

There is also another place where they are doing the same dynamic_cast but it is not in a try block. Could there be any point to a dynamic cast to the same exact type or is that likely just "bad" code?

default
  • 2,637
  • 21
  • 44

2 Answers2

5

My question is, how does this work, if it does?

It doesn't, at least not in any well-defined manner. Trying to do anything with a destroyed non-trivial object gives undefined behaviour.

It's possible that, on some particular implementation, the cast might fail cleanly if the object's been destroyed. But it's just as likely to crash or order pizza.

There are various ways to make sure an object is valid before use - such as smart pointers, or well-structured scopes - but testing the object itself (whether by RTTI or user-declared member data) will not work, since the object can't safely be accessed after destruction.

Does dynamic_cast still do something if the start and end types are the same?

It might do nothing, since it can assume that the pointer is valid, and therefore that the cast will succeed. Or it might do a run-time type check anyway, which will succeed if the pointer is valid, and give undefined behaviour otherwise.

Could there be any point to a dynamic cast to the same exact type or is that likely just "bad" code?

No, there's no point. Either the pointer already points to a valid object of the correct type, in which case you can just use it; or it doesn't, in which case dynamic_cast is undefined.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

dynamic_cast will usually throw an exception if the object it is trying to cast has been freed. This is probably what they mean by "Avoiding a crash"

I think they tossed it in a try block because it was crashing previously, and they didn't want to figure out why it was crashing here.

There's also no reason to dynamic cast to the same exact type unless you're trying to add constness to the variable (arguing that const is a specifier and not part of the type I suppose).

Rubix Rechvin
  • 571
  • 3
  • 16