Portably safe to pass NULL/zero to dynamic_cast?

sdg picture sdg · Mar 1, 2011 · Viewed 18.3k times · Source

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...

Answer

user405725 picture user405725 · Mar 1, 2011

§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.