In the pre-C++11 days it was considered better practice to write:
if (ptr == NULL)
Rather than:
if (!ptr)
This was for two reasons. It is more efficient because it didn't need to cast to bool. And there was no guarantee that the macro NULL
would indeed evaluate to the boolean false
. Is this still true in C++11? Is it preferable to write
if (ptr == nullptr)
Rather than
if (!ptr)
Or is the second fine now?
It is more efficient because it didn't need to cast to bool.
I'd slap an ol' [citation-needed]
at that. I doubt any modern compiler would make that count.
if (ptr)
is perfectly fine and probably more semantically correct, if you're using that value to represent a canonical "lack of value".
I'd only expect to see if (ptr != nullptr)
if someone was actually utilizing the "null" value for pointer arithmetic, but even then it's really sketchy.
That being said, a lot of times you can just get away with... not checking that at all. If the pointer's nullability is used to represent a nullable data field, use optional
. If you are initializing it in case it's empty, use value_or
idiom. If it's just a weak reference and the contract on value is outside, an assert
will do.
Smart pointers like unique_ptr
and shared_ptr
have implicit conversions to bool
that checks the internal pointer against nullptr
, so the second is preferred in those cases, because the intent is well understood.
For raw pointers, I don't know if there's any actual guidance, but ptr != nullptr
certainly explains the intent much more clearly (and what types are involved).
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