NonNull template

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Apr 19 22:23:54 UTC 2025


On Saturday, April 19, 2025 8:23:09 AM MDT kdevel via Digitalmars-d wrote:
> On Saturday, 19 April 2025 at 12:54:27 UTC, Jonathan M Davis
> wrote:
> >>
> >>      [... int *p is potentially null ...]
> >>      enforce (p);
> >>      auto ref r = *p;
> >
> > If it's not doing any additional checks, then I don't
> > understand your point. Of course it's programmer error to
> > convert a pointer to a reference when that pointer is null.
>
>     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 where the programmer screwed up, and
they're going to get a segfault later on if the reference is ever accessed.
If it weren't a valid program, it wouldn't compile. If you had a situation
where a cast were being used to circumvent compiler checks, it could be
argued that it wasn't valid, because the programmer was circumventing the
compiler, but nothing is being circumvented here. Neither language has
checks - either at compile time or at runtime - to catch this issue, so I
don't see how it could be argued that the compiler is providing guarantees
about this or that the program is invalid. In both cases, it's an error on
the programmer's part, and in neither case is the language providing
anything to prevent it or catch it. As far as I can see, the situation in
both cases is identical. Maybe there's some difference in how the C++ spec
talks about it, but there is no practical difference.

- Jonathan M Davis





More information about the Digitalmars-d mailing list