Default struct constructor

Ali Çehreli acehreli at yahoo.com
Wed Jan 27 18:00:02 UTC 2021


On 1/27/21 7:00 AM, Paul wrote:

 > I'd also like to see the possibility for overriding the default struct
 > constructor.

I don't have that feeling anymore. :)

 > I wouldn't say it's absolutely necessary in my case

Same here: Everytime I thought I needed a struct destructor I solved in 
one way or another and never thought about it anymore.

 > I _could_ use a class instead

Classes are so costly though: At least 2 pointers added; 16 bytes on a 
64 bit system. And class variables are references. I would use something 
like the following and be very happy with it:

struct S {
   int i;

   static S opCall() {
     S s;

     import std.random : uniform;
     s.i = uniform(1, 42);

     return s;
   }

   static S defaulted() {
     return S();
   }
}

void main() {
   auto a = S();
   assert(a.i != 0);

   auto b = S.defaulted;
   assert(b.i != 0);
}

Although, I've heard static opCall may have its own set of problems, 
which I haven't encountered yet; other than making the mistake of 
writing 'auto s = S();' as its first line, which causes a segmentation 
fault due to infinite recursion. ;)

 > however I believe a struct is more proper in my scenario.

structs boulder! :)

Ali



More information about the Digitalmars-d mailing list