NonNull template

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Apr 19 11:44:42 UTC 2025


On Saturday, April 19, 2025 5:26:29 AM MDT kdevel via Digitalmars-d wrote:
> On Saturday, 19 April 2025 at 10:35:01 UTC, Jonathan M Davis
> wrote:
> > [...] because then it would need to dereference s to access its
> > i member, but until it needs to access a member, there's no
> > reason for any dereferencing to take place.
> >
> > The same happens with C++ classes as long as the function isn't
> > virtual.
>
> That is undefined behavior. In the C++ standard null references
> have been carefully ruled out [1]. There is no standard
> conforming C++ program having null references.

My point about non-virtual functions and derefencing wasn't really about
references so much as about the fact that the compiler doesn't necessary
dereference when you think that you'r telling it to dereference. It only
does so when it actually needs to.

And whatever is supposed to be defined behavior or not, I have seen pointers
not be dereferenced when calling non-virtual functions - and when creating
references from what they point to.

> > 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.
>
> [1] google.com?q="c++ reference from null pointer"
>      -
> https://old.reddit.com/r/cpp/comments/80zm83/no_references_are_never_null/
>      -
> https://stackoverflow.com/questions/4364536/is-a-null-reference-possible

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.

Either way, unless the compiler inserts checks of some kind in order to try
ensure that a reference is never null, there's no reason to derefence a
pointer or reference until the data it points to is actually used. And
historically, no null checks were done for correctness.

- Jonathan M Davis





More information about the Digitalmars-d mailing list