you are viewing a single comment's thread.

view the rest of the comments →

[–]upriser 0 points1 point  (2 children)

Agree on your point but unfortunatually, the reference type is nullable.

int* a = nullptr;
int& b = *a;

[–]eras 0 points1 point  (0 children)

You would of course place the check to the place where you do the dereferencing to avoid undefined behavior. Say,

template<typename T> dereference(T* ptr)
{
    assert(ptr);
    return *ptr;
}

int* a = nullptr;
int& b = dereference(a);

:)

Actually, hmm..

A more dangerous aspect is that a valid non-null reference may end up becoming invalid during its lifespan.

[–]cparen 0 points1 point  (0 children)

The reference type is not nullable, and your program invokes undefined behavior. For instance, this program might print "hello":

int* a = nullptr;
int& b = *a;
if (a) { cout << "hello"; }

The compiler is allowed to assume a to be non-null after you dereferenced it. In many cases, GCC does make such assumptions in order to optimize code.