4 ms·
>why can't I specify, and have the compiler yell at me if I don't properly handle, "this pointer may never be null" You can do so easily. A reference is a poin
by restes 5y ago
>why can't I specify, and have the compiler yell at me if I don't properly handle, "this pointer may never be null"
You can do so easily. A reference is a pointer that is never null.
- eropple 5y agoC++ isn't C.
- restes 5y agoThe GP was referring to C++ >I would almost never write C++ … Edit: nevermind, I missed the point! GP is saying he wouldn’t write C++ if C supported these features.
- stormbrew 5y ago> 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.
- restes 5y agoCompilers 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?
- stormbrew 5y ago"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).