|
|
|
|
|
by Animats
38 days ago
|
|
In C++, that distinction supposedly exists. References should never be null, while pointers can be. But there's no enforcement. int& ref = *ptr;
ought to generate a panic for a null pointer. But it doesn't. They were so close to getting it right. |
|
When you write `int& ref = *ptr;` you are dereferencing the pointer with `*ptr` therefore you have promised that it's valid. The compiler doesn't need to do anything to validate ptr because it already has your assurance.
It's really no different than if you were to write `printf("%d", *ptr);`. It's only a little weird because in `ref = *ptr;` the compiler doesn't actually emit any instruction for the dereference, but that doesn't mean that the assurance you gave doesn't exist.
It would indeed be problematic were it to be `int& ref = ptr;` without the dereference but it's not.