Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cast nullptr to other pointer type?

Tags:

Can I do this?

static_cast<A*>(getSomePtr()); 

where getSomePtr() will return nullptr. Is this ok?

like image 823
Narek Avatar asked Nov 11 '15 14:11

Narek


2 Answers

From Wikipedia article:

...null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool.

nullptr is implicitly convertible to any pointer type so explicit conversion with static_cast is absolutely valid.

like image 128
Lukáš Bednařík Avatar answered Oct 21 '22 02:10

Lukáš Bednařík


I suspect that you are confused about the difference between a null pointer and nullptr, they are not the same.

This function returns nullptr:

std::nullptr_t getNullPtr() { return nullptr; } 

But that is a pretty useless thing to return, there is very rarely a good reason to return an object of that type.

This function returns a null pointer:

A* getAPtr() { return nullptr; } 

The return value is initialized with nullptr but it is actually a null pointer of type A*, not nullptr itself.

For the first function, yes, you can cast the returned std::nullptr_t to another pointer type (you don't even need a cast to do the conversion, it will happen implicitly) but that's probably not something you ever want to do.

For the second function you don't need to cast it because it already returns the right type.

like image 27
Jonathan Wakely Avatar answered Oct 21 '22 01:10

Jonathan Wakely