Portably safe to pass NULL/zero to dynamic_cast?

C++NullDynamic Cast

C++ Problem Overview


Out of habit for checking null pointers, I have sometimes written:

MyClass * c = someBasePtr ? dynamic_cast<MyClass*>(someBasePtr) : 0;
if (c) {...

In effect, checking for a null pointer before passing to dynamic cast, and also checking the return.

I then read in the MSDN documentation

> A null pointer value is converted to > the null pointer value of the > destination type by dynamic_cast.

It appears then that I could remove the ?: construct safely. Is this C++ portable?

Such that the new code would be

MyClass * c = dynamic_cast<MyClass*>(someBasePtr);
if (c) {...

Of course presuming that someBasePtr is either null or valid, i.e. not wild pointing to garbage...

C++ Solutions


Solution 1 - C++

§5.2.7/4:

> If the value of v is a null pointer > value in the pointer case, the result > is the null pointer value of type R.

So you don't have to check for a null pointer yourself. Same goes for operator delete, deleting a null pointer has no effect.

Solution 2 - C++

Yes, you can use dynamic_cast on a null pointer.

Solution 3 - C++

Yes, check 5.2.7.4 in standard.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsdgView Question on Stackoverflow
Solution 1 - C++user405725View Answer on Stackoverflow
Solution 2 - C++sharptoothView Answer on Stackoverflow
Solution 3 - C++ssegvicView Answer on Stackoverflow