jmasterx jmasterx - 3 months ago 13
C++ Question

Checking for a null reference?

Lets say you have something like this:

int& refint;
int* foo =0;
refint = *foo;


How could you verify if the reference is
NULL
to avoid a crash?

Answer

You can't late-initialize a reference like that. It has to be initialized when it's declared.

On Visual C++ I get

error C2530: 'refint' : references must be initialized

with your code.

If you 'fix' the code, the crash (strictly, undefined behaviour) happens at reference usage time in VC++ v10.

int* foo = 0;
int& refint(*foo);
int i(refint);  // access violation here

The way to make this safe is to check the pointer at reference initialization or assignment time.

int* foo =0;
if (foo)
{
  int& refint(*foo);
  int i(refint);
}

though that still does not guarantee foo points to usable memory, nor that it remains so while the reference is in scope.