LWN.net Logo

C and C++ could have non_nullable pointers, easily

C and C++ could have non_nullable pointers, easily

Posted Sep 9, 2009 6:35 UTC (Wed) by cmccabe (guest, #60281)
In reply to: C and C++ could have non_nullable pointers, easily by hummassa
Parent article: Null pointers, one month later

C++ does have non nullable pointers. They're called references.

References must point to valid objects.


(Log in to post comments)

C and C++ could have non_nullable pointers, easily

Posted Sep 9, 2009 14:28 UTC (Wed) by foom (subscriber, #14868) [Link]

The only problem is that:
Obj *p = 0;
Obj &r = *p;

is perfectly valid. So they don't make a very good non-nullable pointer.

C and C++ could have non_nullable pointers, easily

Posted Oct 18, 2009 22:52 UTC (Sun) by cmccabe (guest, #60281) [Link]

> The only problem is that:
> Obj *p = 0;
> Obj &r = *p;
>
> is perfectly valid. So they don't make a very good non-nullable pointer.

There shall be no references to references, no arrays of references, and no pointers to references. The declaration of a reference shall contain an initializer (8.5.3) except when the declaration contains an explicit extern specifier (7.1.1), is a class member (9.2) declaration within a class declaration, or is the declaration of a parameter or a return type (8.3.5); see 3.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 bitfield. ]

—ISO/IEC 14882:1998(E), the ISO C++ standard, in section 8.3.2 [dcl.ref]

C.

C and C++ could have non_nullable pointers, easily

Posted Oct 19, 2009 3:47 UTC (Mon) by foom (subscriber, #14868) [Link]

> a null reference cannot exist in a well-defined program

I stand corrected.

I had always considered the "dereference" that occurs during the initialization of a reference
variable as syntax, rather than an actual memory operation, and thus the value of the pointer is
irrelevant at that point. Clearly the standard says otherwise.

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds