Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!spool.mu.edu!uunet!fernwood!lia!jgro From: jgro@lia (Jeremy Grodberg) Newsgroups: comp.lang.c++ Subject: Null references Message-ID: <1991Feb13.224743.1123@lia> Date: 13 Feb 91 22:47:43 GMT Reply-To: jgro@lia.com (Jeremy Grodberg) Lines: 58 I've been looking through the ARM to try to find out how Null pointers and references work together, and I can find neither any guarantees nor any statments that the behaviour is undefined. Here is a very simple example of what I want (it is of course too simple to be useful). #define NULL 0 int* square(int& x) { if (&x != NULL) x *= x; return &x; } main() { int* p = NULL; int& death = *square(*p); // I want a *guarantee* that this will not crash death = 0; // Of course, this causes a run-time crash } In other words, I want a guarantee that pointers are not dereferenced when initializing references. This is in fact the observed behavior of CFront 2.0. It is useful in some circumstances when you want to preserve object semantics with references, but occasionally have a null object reference. For example, suppose I want to implement a look-up table, and my find() function needs to return an object. It is much more efficient to return an object reference, but I would like to return NULL if I can't find the requested object. I currently have no guarantee that this will work, and my only other solution is to return an object pointer. This makes references less useful, and burdens the rest of my code with creating temporary pointers to hold the return results so I can check it against NULL before converting it to a reference. There are other situations in which null references substantially clean up the code. Since we already have all sorts of special case treatment of null pointers, and since we are guaranteed that the address (&) of a reference is the same as the address of the object which it refers to, it doesn't seem like such an extra burden to allow the creation of null references. If the ANSI comittee thinks this guarantee is too hard to make, and/or just isn't worth the effort, then I would like a statment to that effect added to the standard, so that we can all know this is non-portable, and so that people realize that null reference might be allowed by the compiler. For example, if the initialization of "death" in my example is successful, some people will take that to mean that "death" refers to a valid object, and be totally confused when the simple assignement statement cause a crash. The statement that null references have undefined behaviour will help alert people to that situation. -- Jeremy Grodberg "I don't feel witty today. Don't bug me." jgro@lia.com