Hacker News new | ask | show | jobs
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.

1 comments

> When you write `int& ref = ptr;` you are dereferencing the pointer with `ptr` therefore you have promised that it's valid.

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.

The danger and utility of pointer are two sides of the same coin. You can reduce the need for pointers but not eliminate them completely if you want to be able to call C functions or build low-level data structures.

The real problem is that references are not good enough in C++, so some C++ developers end up using pointers for everything. Rust's references are good enough that you can avoid using pointers most of the time.