Dynamic_cast object for the same type

I am working on some legacy code that has multiple lines:

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

      

Where is _object

already there Object*

to start. The code has a comment about trying to avoid crashing when _object

was released. My question is, how does it work if it does? Does it dynamic_cast

do something if the start and end types are the same?

There is another place where they do the same dynamic_cast

, but not in the try block. Could there be some point for dynamically casting to the same exact type, or is this most likely "bad" code?

+3


source to share


2 answers


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

It is, at least not in any clearly defined form. Trying to do something with a destroyed non-trivial object gives undefined behavior.

It is possible that in a particular situation, the throw may fail if the object has been destroyed. But it is just as likely that a crash or a pizza order.

There are various ways to ensure that an object is valid prior to use - such as smart pointers or well-structured scopes - but testing the object itself (be it RTTI or user-declared element data) will not work because the object cannot be safely accessed after destruction.



Does it dynamic_cast

do something if the start and end types are the same?

It cannot do anything, since it can assume that the pointer is valid and therefore the cast will succeed. Or it can do runtime type checking, which will succeed if the pointer is valid, and give undefined behavior otherwise.

Could there be some point for dynamically casting to the same exact type, or is this most likely "bad" code?

No, it doesn't make sense. Or the pointer already points to a valid object of the correct type, in which case you can simply use it; or not, in which case dynamic_cast

undefined.

+5


source


dynamic_cast usually throws an exception if the object it is trying to execute has been deallocated. This is probably what they mean by "Crash avoidance"

I think they threw it in a try block because it collapsed earlier and they didn't want to understand why it collapsed here.



There is also no reason to dynamically cast to the same exact type unless you are trying to add a constant to the variable (by claiming that const is a specifier and not part of the type I assume).

+1


source







All Articles