DMD 0.177 release

Walter Bright newshound at digitalmars.com
Sat Dec 9 19:37:31 PST 2006


Tom S wrote:
> A static opCall 
> won't handle the following case:
> 
> ----
> 
> void delegate() globalDG;
> 
> 
> struct Foo {
>     void func() {
>         printf("myVal = %d\n", myVal);
>     }
> 
>     static Foo opCall(int v) {
>         Foo res;
>         res.myVal = v;
>         globalDG = &res.func;
>         return res;
>     }
> 
>     int myVal;
> }
> 
> 
> void main() {
>     Foo f = Foo(5);
>     globalDG();  // prints garbage instead of '5'
> }
> 
> ----

Ok, you're right on that one. But I am going to argue on philosophical 
grounds that this kind of code is incorrect for a couple of reasons:

1) constructors should construct objects, not set state outside themselves.

2) trying to keep track of every struct created is going to put a hole 
below the waterline in some new capabilities planned for the future. The 
compiler needs to be able to willy-nilly create bit copies of structs 
for this to work. C++ has this problem in spades (just follow the 
skin-rending and hair-pulling going on with the "move constructor" 
issues). Allowing the compiler to be able to create bit copied 
temporaries without needing to call constructors is going to be 
worthwhile by enabling some pretty cool stuff.

I'm going to put forward the idea that this kind of thing should be done 
with classes, not structs.


> The Foo instance returned from static opCall is copied, thus the 'ctor 
> hack' doesn't have real access to the object it's constructing, not to 
> mention the overhead of copying the struct to another place on stack...

It's time to put the recurring efficiency argument to bed. Consider this 
D code:
-------------------
  struct S
  {
      static S opCall(int v)
      {
          S result;
          result.v = v;
          return result;
      }
      int v;
  }

  int test()
  {
     auto s = S(5);
     return s.v;
  }
------------compiles to----------
  _D4test1S6opCallFiZS4test1S     comdat
                  ret
  _D4test4testFZi comdat
                  mov     EAX,5
                  ret
---------------------------------
It doesn't get any better than that.


> Also,  new Foo(5)  isn't going to work without real ctors or more hacks.

That can be supported without any more work than supporting it with ctors.



More information about the Digitalmars-d-announce mailing list