Nullptr and NULL question

Example

Case1
Something* MyPtr = nullptr;
if (MyPtr) // returns true

//============

Case2
Something* MyPtr = NULL;
if (MyPtr) // returns false

Question

I typical use case 2 above, to simplify my code readability. But I was looking into nullptr and decided it makes more sense and clearly defines the variables as a ptr when seen.

But as seen in the cases above it throws true when queried in an if statement. If I start using nullptr should I just begin writing all my code as follows:

Something* MyPtr = nullptr;
if (MyPtr != nullptr) // returns true

This seems a lot less clear, and messy.

TL:DR

Can anyone advise me on the proper way to use nullptr or if it’s even UE4 C++ recomended?

nullptr should return false. MyPtr != nullptr should also return false.

x was 1 at the end of the following code:

static int x = 1;
void* MyPtr = nullptr;
if (MyPtr)
{
	x++;
}

if (MyPtr != nullptr)
{
	x *= 100;
}

// x still == 1

You should be able to use nullptr exactly like you use NULL or 0 for pointers. I use it just fine.

Unless your compiler is doing something really strange, nullptr should evaluate to 0 by default. You can read in the UE4 coding standards that they prefer using nullptr but leave NULL defined as well as it is prevalent through the existing code base.

The old macros ‘checkAtCompileTime’, ‘OVERRIDE’, ‘FINAL’, and ‘NULL’ can now be replaced with ‘static_assert’, ‘override’, ‘final’, and ‘nullptr’. Some of these macros may remain defined as their use is still prevalent.

I’ve used nullptr almost exclusively for a while now and haven’t had to alter my normal “if” habits when checking for pointer safety.

More discussion on this:

You could put a break point at that check and see exactly nullptr (and thus std::nullptr_t) is defined as.

Thanks for the example, it works for me too. I have no idea why my code was registering true. I edited my code, and recompiled again and it worked. I don’t understand why it was returning true. It would return true then attempt to access a value and crash.

If it happens again I will try to debug it more thoroughly.

Thank you for the details. It’s nice to know nullptr is the more standard.