1
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?

6
  • 6
    Undefined behavior is undefined. Commented Jan 6, 2015 at 16:14
  • @T.C. Which is undefined, referencing to pointer, or referencing to null pointer? Commented Jan 6, 2015 at 16:15
  • I don't think dereferencing yields a temporary, that's why you can take the address of it. Commented Jan 6, 2015 at 16:17
  • 1
    "Still pointer to reference is allowed?" – no it isn't. But there's no pointer to reference anywhere in this piece of code. Commented Jan 6, 2015 at 16:17
  • @PranitKothari: Dereferencing a null pointer is undefined. That is, the expression *ptr causes undefined behavior. Commented Jan 6, 2015 at 16:18

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This might be a purely language-laywer remark, but it can be argued that dereferencing a null pointer does not cause undefined behaviour. On the other hand, it seems the committee is opposed to introducing null references. That means, the two are unrelated. See open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232
@dyp: Indeed, there's enough ambiguity in the standard here to argue that, if you care about that level of pedantry. But it's off-topic here; it's certainly UB to use the result to initialise a reference, since it doesn't refer to a valid object.
Technically the quoted sentence of 8.3.2/5 requires a diagnostic (it's not marked with "no diagnostic required"), which would of course be completely unrealistic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.