NonNull template
kdevel
kdevel at vogtner.de
Sat Apr 19 23:51:58 UTC 2025
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".
> [...] If it weren't a valid program, it wouldn't compile.
That is an interesting opinion.
More information about the Digitalmars-d
mailing list