NonNull template

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Apr 20 00:33:52 UTC 2025


On Saturday, April 19, 2025 5:51:58 PM MDT kdevel via Digitalmars-d wrote:
> On Saturday, 19 April 2025 at 22:23:54 UTC, Jonathan M Davis
> wrote:
> >>
> >>     int main ()
> >>     {
> >>        int *p = NULL;
> >>        int &i = *p;
> >>     }
> >>
> >> That is an error (mistake) only in C++ because the reference
> >> is not initialized with a valid initializer. In D, however,
> >>
> >>     void main ()
> >>     {
> >>        int *p = null;
> >>        ref int i = *p; // DMD v2.111.0
> >>     }
> >>
> >> is a valid program [3].
> >
> > In both cases it's a valid program
>
> Only the D version is valid. The C++ program violates the std.
>  From the SO page there is a quote of the C++ 11 std draft which
> says in sec. "8.3.2 References":
>
>      "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.
>       [...] — end note ]"
>
> You find nearly the same wording in sec. 11.3.2 of the C++17 std
> draft (N4713) and in sec. 9.3.4.3 of the C++23 std draft (N4928)
> with the "dereferencing" replaced with "indirection".

I see no practical difference in general, but I guess that the difference
would be that if C++ says that the behavior is undefined, then it can let
the optimizer do whatever it wants with it, whereas D has to say at least
roughly what would happen, or the behavior would be undefined and thus screw
up @safe. Whatever assumptions the optimizer may make about it, they can't
be anything that would violate memory safety.

In practice though, particularly with unoptimized code, C++ and D are going
to do the same thing here, and in both cases, the programmer screwed up, so
their program is going to crash. And realistically, it'll likely do the same
thing in most cases even with optimized code.

- Jonathan M Davis






More information about the Digitalmars-d mailing list