76

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

sdg
  • 4,645
  • 3
  • 32
  • 26

3 Answers3

101

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

24

Yes, you can use dynamic_cast on a null pointer.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
6

Yes, check 5.2.7.4 in standard.

ssegvic
  • 3,123
  • 1
  • 20
  • 21