4 ms·
C++ references can easily be null (T& foo = *ptr_i_thought_was_good;). But they provide a useful social convention: if it is a pointer then it is your job to c
by adrianratnapala 10y ago
C++ references can easily be null (T& foo = *ptr_i_thought_was_good;).
But they provide a useful social convention: if it is a pointer then it is your job to check for NULL. If it is a reference, then it is the job of the other guy to ensure it is not null. And the rules of the language mean that null references (as opposed to pointers) are rare.
- shultays 10y agoNot without an UB
- ArkyBeagle 10y agoIf you never dereference a null pointer, then there will be no UB of that type.
- shultays 10y agoI guess it counts as dereferencing. Here is what standard says "A reference shall be initialized to refer to a valid object or function. 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"
- adrianratnapala 10y agoSo in other words my comment should have said that: in C++ it is easy to create something that is either a null-reference or some other, much more unpredictable, undefined thing. Well then! That just goes to show how much safer C++ references are than I had previously supposed.