3 ms·
A minor nit: There is a major difference between Rust references and C++ references - while both are guaranteed to point at something, only a Rust reference is
by dagenix 8y ago
A minor nit: There is a major difference between Rust references and C++ references - while both are guaranteed to point at something, only a Rust reference is guaranteed to point at something valid. A C++ reference can point at an already freed object if you aren't careful which can be worse than a NULL pointer dereference since this can cause silent corruption.
- saurik 8y agoCan you define better "guaranteed"? If you take a NULL pointer and dereference it you get a null reference. I realize the language standard insists this isn't possible, and so compiler developers have started feeling justified in saying "if (&myref == NULL)" is nonsense they can "optimize out" (as if I somehow typed that by mistake :/...); but that is just the compiler making an unwarranted and clearly incorrect "assumption": nothing in any of the language standard, the compiler, or the runtime "guarantees" that references point at something. If dereferencing a pointer was required to do a one byte read from the address that could not be elided by the compiler, or automatically injected the moral equivalent of "if (myptr == NULL) std::terminate();", that would be an entirely different story; but, as it stands, a dereference from a pointer to a reference is nothing more than a blind type assertion by the developer, and so there is no reason to believe a reference is somehow any less likely to be NULL than a pointer the developer always thought would point to something.
- saagarjha 8y ago> compiler developers have started feeling justified in saying "if (&myref == NULL)" is nonsense they can "optimize out" (as if I somehow typed that by mistake :/...); but that is just the compiler making an unwarranted and clearly incorrect "assumption": nothing in any of the language standard, the compiler, or the runtime "guarantees" that references point at something I don't see how there is nothing guaranteeing that your references are nonnull. My understanding was that the standard prevents you from having a null reference because the methods of trying to generate one are codified as illegal or performing undefined behavior. Am I wrong here, or misunderstanding what you're trying to say?
- dagenix 8y agoI'm not a C++ standard expert, but, here is my understanding: In C++, if you have a reference, it must refer to something. I'm not aware of any way to legally construct a reference that refers to NULL. Of course, we live in the real world, where, regardless of what the C++ standards say, anything is possible. A random bit-flip could cause the reference to refer to NULL. But, AFAIK, thats outside of the C++ standard.