On Wednesday, 24 January 2018 at 02:01:54 UTC, Jonathan M Davis wrote:
On Wednesday, January 24, 2018 01:48:45 Alex via Digitalmars-d-learn wrote:
the story of https://forum.dlang.org/thread/qknxjxzbaowmsjdng...@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);


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.

That's cool, by the way :)

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.


Reply via email to