NonNull template

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


On Saturday, April 19, 2025 6:13:36 AM MDT kdevel via Digitalmars-d wrote:
> On Saturday, 19 April 2025 at 11:44:42 UTC, Jonathan M Davis
> wrote:
> > [...]
> >> > And with
> >> >
> >> > int* p = null;
> >> > ref r = *p;
> >> >
> >> > no dereferencing occurs,
> >>
> >> In C++ this is a programming error. When creating a reference
> >> from a pointer the null check it is necessary in order to
> >> uphold
> >> C++' guarantee that references are actually bound to existing
> >> objects.
> >> [...]
> >
> > Well, if C++ now checks that pointer is non-null when creating
> > a reference from it, that's new behavior, because it most
> > definitely did not do that before.
>
> Of course it doesn't and I didn't write that. I wrote that it is
> a programming error to use a ptr to initialize a reference when
> it is possible that the ptr is null. If refs in D were as strong
> as in C++ I would write
>
>      [... 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. It's the same programmer error as any time that you
dereference a null pointer except that it doesn't actually dereference the
pointer when you create the reference and instead blows up later when you
attempt to use what it refers to, because that's when the actual
dereferencing takes place. If C++ doesn't have additional checks, then it's
not any stronger about guarantees with & than D is with ref.

Meta was asking how it was possible that

int* p = null;
ref r = *p;

would result in a null reference instead of blowing up, and I explained why
it didn't blow up and pointed out that C++ has the exact same situation. And
unless C++ has added additional checks (and it sounds like they haven't),
then there's no real difference here between C++ and D.

- Jonathan M Davis





More information about the Digitalmars-d mailing list