NonNull template

kdevel kdevel at vogtner.de
Sat Apr 19 14:23:09 UTC 2025


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].

> 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.

Assume the "dereference" of the pointer and the initialization
of the reference happen in different translation units written
by different programmers. I.e.

tu1.cc

    void foo (int &i)
    {
    }

tu2.cc

    int main ()
    {
       int *p = NULL;
       foo (*p);
    }

versus

tu1.d

    void foo (ref int i)
    {
    }

tu2.d

    int main ()
    {
       int *p = NULL;
       foo (*p);
    }

Then we have different responsibilities. In the C++ case the
programmer of tu2.cc made a mistake while in the D case the
code of tu2.d is legit. I would not call this situation "the
same programmer error".

> If C++ doesn't have additional checks, then it's not any 
> stronger about guarantees with & than D is with ref.

As programmer of translation unit 1 my job is much easier if I
use C++.

[3] https://dlang.org/spec/type.html#pointers
     "When a pointer to T is dereferenced, it must either contain 
a null
     value, or point to a valid object of type T."



More information about the Digitalmars-d mailing list