static weirdness

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jan 24 02:01:54 UTC 2018


On Wednesday, January 24, 2018 01:48:45 Alex via Digitalmars-d-learn wrote:
> the story of
> https://forum.dlang.org/thread/qknxjxzbaowmsjdngvli@forum.dlang.org
> continues
>
> How can this be?
>
> void main()
> {
>      auto s = S();
>      auto t = T!s();
>      assert(typeof(t).dummy == null);
>      assert(t.dummy == null);
>      t.foo;
>
> }
>
> struct S
> {
>      auto fun()
>      {
>       return 42;
>      }
> }
>
> struct T(alias stats)
> {
>      static typeof(stats)* dummy; // line 21
>      static auto foo()
>      {
>       assert(dummy == null); // line 24
>          assert(dummy.fun == 42); //line 25
>      }
> }
>
> I thought, if I don't initialize a pointer, like the one in line
> 21 (I assert this by the check in line 24) I can't use it line
> line 25.
> However, I can...

That has nothing to do with static. That has to do with the fact that S.fun
is non-virtual (so there's no need to dereference the pointer to call it),
and fun doesn't access any members, so it doesn't need to dereference the
this pointer internally either. And since the pointer is never dereferenced,
it doesn't matter that it's null. You'd get the same behavior if you used
a non-static S.

On a side note, if you're checking for null, it's better to use the is
operator rather than ==. For strings, there's a semantic difference, so it
really matters. For classes, it avoids calling the free function opEquals
(which will give the same result, but it's a pointless function call when
you could just use is and avoid the call). For pointers, it matters that
much less, but since it does matter in the other cases (especially strings),
it's a good habit to get into just using is null instead of == null.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list