Hacker News new | past | comments | ask | show | jobs | submit login

I've gotten into arguments about this in the past.

As you've shown, references can be null, but theyre not supposed to be and are assumed nearly universally to not be.

The argument comes down to when the undefined behavior occurs: is it at the deference to create the reference, or is it on the first memory access using the reference? The language pedants will say the former, but in practice, it's the latter.

In practice, you'll likely be able to invoke a member function on a null pointer or reference, as long as that member doesn't directly or indirectly access data members, or virtual functions of the type. Obligatory, I dont recommend doing this or relying upon this behavior, it's just behavior I've seen in my 2 decades of debugging C++.




It's mostly important in the context of codifying nullability. If a function returns a reference it's part of the contract that it doesn't return null. Similarly, if a parameter is a reference it's part of the contract that you can't pass it null.

It doesn't mean a method that takes or returns a pointer must allow null as a valid value, of course, Optional<> is better for that. But standards-enforced non-null is a very practically useful aspect of references that differ them from pointers.


> The argument comes down to when the undefined behavior occurs: is it at the deference to create the reference, or is it on the first memory access using the reference? The language pedants will say the former, but in practice, it's the latter.

The undefined behavior is always when the null reference is created. The issue will _usually_ manifest when you try to dereference the pointer, but the undefined behavior was creating the null reference in the first place.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: