Is it safe to port NULL / zero to dynamic_cast?

Out of habit for checking null pointers, I sometimes wrote:

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

In fact, checking the null pointer before moving on to the dynamic hyphenation, as well as checking the return.

Then I read in the MSDN documentation

A null pointer value is converted to a null pointer destination type dynamic_cast.

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

So the new code will be

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

Of course, assuming that someBasePtr is either null or real, i.e. not wild pointing to trash ...

+42
c ++ null dynamic-cast
Mar 01 2018-11-11T00:
source share
4 answers

Β§5.2.7 / 4:

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

This way you do not need to check the null pointer yourself. The same goes for deleting a statement; deleting a null pointer has no effect.

+57
Mar 01 2018-11-11T00:
source share

Yes, you can use dynamic_cast for a null pointer.

+20
Mar 01 2018-11-11T00:
source share

Yes, check the standard 5.2.7.4.

+4
Mar 01 2018-11-11T00:
source share

I was curious about this and tried this before looking for this answer. The following code does not cause errors in C ++ 14.

 class A { public: virtual ~A() {} }; class B: A {}; #include <iostream> int main() { A* error_pointer = nullptr; B* x = dynamic_cast<B*>(error_pointer); std::cout<<"No errors :)\n"; } 

Test it here: http://ideone.com/0dSf5p

0
Jan 18 '16 at
source share



All Articles