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

> A reference is a pointer that is never null.

This isn't even theoretically true:

    void blah(int &x) { x++; }

    int main() {
      int *x = NULL;
      blah(*x);
    }
You can definitely write a smart pointer that more or less provides some kind of guarantee about this (with a combo of runtime checks and typefoo) but references only provide a guarantee that they are not statically initializable to null, which is very different.



Compilers are free to assume x is non-null at the time it’s dereferenced, so isn’t it true by definition? Do you have an example that doesn’t rely on undefined behavior?


"Compilers are free to assume" is a fine thing for like, a loop, but the compiler isn't free to assume you didn't mean to dereference the reference in the code snippet I posted, it's just free to not check before it does.

So it will crash, whether that's undefined behaviour or not. The thing at issue here is that other languages have reference types that are more strictly statically guaranteed to be non-null. My point is that references are not a substitute for those, because holding them wrong is not only easy, it's extremely likely to happen in code of any reasonable complixity that mixes pointers and references (ie. almost all production C++ code).




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

Search: