Pranit Kothari
Pranit Kothari

Reputation: 9841

Why reference to indirection to pointer is allowed?

int *ptr = 0;
int &ref = *ptr;

I write above code in Visual Studio and it works? Here I am pointing to NULL. Why it is allowed? Pointer can take any address, NULL or even invalid address. Still reference to indirection of pointer is allowed?

Then why it is said "Reference cannot be null." Here, is reference not pointing to NULL?

Upvotes: 1

Views: 191

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

It's not allowed.

In the words of the standard:

C++11 8.3.2/5: A reference shall be initialized to refer to a valid object or function.

However, it's not something that the compiler can, in general, diagnose, since the validity of a pointer is a run-time thing. So there's no requirement to diagnose the error, and probably no compiler warning, just undefined behaviour.

The standard specifically mentions this case:

Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

Upvotes: 14

Related Questions