4 ms·
We can quibble on definitions here, but a reference in C++ can not be null. The undefined behavior happens before any assignment to a reference is executed so t
by Maxatar 2y ago
We can quibble on definitions here, but a reference in C++ can not be null. The undefined behavior happens before any assignment to a reference is executed so that at the moment that the assignment happens, the reference is guaranteed to not be null.
In your example, it's the dereference of the pointer to p that is undefined behavior, so anything that happens after that point is also undefined behavior. Note that means there is never an actual assignment to r if p is null.
As I mentioned earlier, this might seem like quibbling with definitions, but this is the proper mental model to have with respect to C++'s semantics.
Having said that, I don't disagree with the main crux of your point, which is that C++'s semantics are terrible and there is little that the language provides to write correct code, but I do think there are subtleties on this matter that are worth clarifying.
- tsimionescu 2y agoI agree, but by that same definition, a private reference field in Java that is initialized in the constructor also can't be null. My point is that we can compare two things: valid programs, or programs that compile. In valid C++ programs, references can't be null and there are no data races. In valid Java programs, all final fields initialized in an object's constructor have that value for the lifetime of the object. If we compare invalid programs that compile, which is an important point as well, then those guarantees go out the window. But here Java is much more forgiving than C++: if you have improper synchronization, you may see fields which are null instead of having their final value, which is bad and confusing. But in C++ with improper synchronization, you can see literally any outcome at all.