Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting nullptr to bool

Tags:

c++

c++11

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?

like image 856
Benjy Kessler Avatar asked Dec 05 '22 04:12

Benjy Kessler


2 Answers

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.

like image 99
Bartek Banachewicz Avatar answered Dec 28 '22 09:12

Bartek Banachewicz


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

like image 35
AndyG Avatar answered Dec 28 '22 09:12

AndyG