|
|
|
|
|
by zarzavat
38 days ago
|
|
There's nothing particularly special about null pointers: you can also have an invalid non-null pointer, e.g. through pointer arithmetic. 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. |
|
Yes, that's exactly the problem. "I promise I didn't make a mistake when reasoning about this code" is tied for worst strategy in the world for preventing bugs, along with every other strategy that doesn't actually prevent bugs.