struct construction (how?)

Ali Çehreli acehreli at yahoo.com
Sun Dec 27 23:56:48 PST 2009


Coming from C++ and reading the D2 spec, I realized that I don't 
understand struct construction yet. :) I am playing with dmd 2.037.

Considering

struct S
{
     int x;
     int y;
}

which may have a

     this(int x, int y)

defined:

1)

S s = { 1 };

Not good; because we may forget to provide initializers and the 
remaining members are not even default initialized. (I wrote about this 
recently; I hope it's just a bug and will get fixed.)

2)

S s;
s.x = 1;
s.y = 2;

Not good; because that is default initialization plus assignment. Also, 
we shouldn't be doing that everywhere in user code; it should be the job 
of the constructor.

3)

auto s = S(1, 2);

Not good, because the right hand side is a struct literal and there is a 
copy involved.

Also, that syntax fails if S also has an opCall defined.

4)

S s(1,2);

Does not work.

5) S(1,2) s;

My favorite, but does not work.

How do you construct a struct object? Am I giving structs too much 
attention? Should I just know that they exist but use classes instead?

Thank you,
Ali


More information about the Digitalmars-d-learn mailing list