Casting nullptr to bool

c++, c++11

Solution

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.

Problem

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?

Original source

Related problems