|
|||||||||||||||||
|
Section 8:
|
[8.7] What does it mean that a reference must refer to an object, not a dereferenced NULL pointer?
It means this is illegal: T* p = NULL; T& r = *p; ← illegalNOTE: Please do not email me saying the above works on your particular version of your particular compiler. It's still illegal. The C++ language, as defined by the C++ standard, says it's illegal; that makes it illegal. The C++ standard does not require a diagnostic for this particular error, which means your particular compiler is not obliged to notice that p is NULL or to give an error message, but it's still illegal. The C++ language also does not require the compiler to generate code that would blow up at runtime. In fact, your particular version of your particular compiler may, or may not, generate code that you think makes sense if you do the above. But that's the point: since the compiler is not required to generate sensible code, you don't know what the compiler will do. So please do not email me saying your particular compiler generates good code; I don't care. It's still illegal. See the C++ standard for more, for example, section 8.3.2p4. By way of example and not by way of limitation, a compiler might optimize a NULL test since it "knows" all references refer to real objects — that references are never (legally) a dereferenced NULL pointer. That might cause a compiler to optimize away the following test:
...the above code...
T* p2 = &r;
if (p2 == NULL) {
...
}
As stated above, this is just an example of the sort of thing
your compiler might do based on the language rule that says a reference must
refer to a valid object. Do not limit your thinking to the above
example; the message of this FAQ is that the compiler is not required to do
something sensible if you violate the rules. So don't violate the rules.
|
||||||||||||||||