Can I do this?
static_cast<A*>(getSomePtr());
where getSomePtr()
will return nullptr
. Is this ok?
From Wikipedia article:
...null pointer constant:
nullptr
. It is of typenullptr_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 forbool
.
nullptr
is implicitly convertible to any pointer type so explicit conversion with static_cast
is absolutely valid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With