When bad C++ code tries to create a null reference like the following:
int &ptr2ref(int *p){
return *p;
}
int calc(int &v){
return v*2;
}
...
int &i = ptr2ref(nullptr);
calc(i);
At least in Visual C++ it crashed in the return statement of function calc
(debug mode).
However, the answer of this question quotes
8.3.2/1:
A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
1.9/4:
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)
If I understand right, the standard said that as soon as a null reference being created the program behavior is being undefined. So if a compiler intended to generate useful debug information it should crash at function ptr2ref
in the above example, since there is where the null reference being created (and the deferencing happening).
Am I missed something? Are there any issue stops the compiler generate such code in at lest debug mode?
Undefined Behaviour
I know people will argue that "undefined" means roughly everything. My argument is, given the fact that the standard did not specify how long a simple int main(){}
shall take to compile, no one will accept a compile time to be more than a day. So the problem is about implementation options, not the standard itself. I quoted the standard here is just to say that crash on ptr2ref
IS an option.
Furthermore, there is already a lot of additional checking happening in debug mode, for example, the stack was always checked to see if there are any corruption before returning from the function. Compare to those I don't think add a relatively simple check will be too expansive in debug mode.