Struct Constructor Lazy

Biotronic via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 12 04:18:08 PDT 2017


On Wednesday, 12 July 2017 at 11:00:54 UTC, Jiyan wrote:
> Hey there:)
>
> i want to know whether the following is somehow possible:
> structs dont have default constructors, i know so:
>
> struct A
> {
> int field;
> this(int i){field = getDataFromFile("file.txt");}
> }
>
> A instance = A(0);
>
> Here comes my issue:
> when A(0) is called I would want here optimal performance, so 
> there doesnt even need to be a value pushed on the stack (i=0), 
> what would be like having a constructor with zero arguments (i 
> is never used!).
> Im pretty new to D, can somebody tell me how i would do this?
> Is this(lazy int i){ ... a solution?

The traditional solution is static opCall:

struct A {
     int field;
     static A opCall() {
         A result;
         result.field = getDataFromFile("file.txt");
         return result;
     }
}

A instance = A();

I believe I've heard this is frowned upon these days, but I don't 
know of a better solution.

For optimal speed you might also want to skip default 
initialization of result, by writing A result = void;.

I would be surprised if the optimizer wasn't able to optimize 
away the useless parameter though - have you looked at the 
generated assembly?

--
   Biotronic


More information about the Digitalmars-d-learn mailing list