How to define a constructor in a struct?

Jonathan M Davis jmdavisProg at gmx.com
Sun Aug 5 13:46:43 PDT 2012


On Sunday, August 05, 2012 19:28:30 Jacob Carlborg wrote:
> On 2012-08-05 18:30, Minas Mina wrote:
> > Thank you. Is it the way it is to have compatibility with C structs?
> 
> No, I don't think so. If I recall correctly it has something to do with
> the .init property and the compiler need to know the initialization code
> of the sturct at compile time.

Exactly. Every type in D must have an init value. So when you do

T value;

or

T[10] array;

the data isn't garbage. That's straightforward enough for the built-in types 
(0 for integral types, NaN for floats, false for bool, etc.) and pointers and 
references are null, so it's not a problem for classes either. But for structs 
- which normally go on the stack - it's more problematic. init must be the 
state of the whole struct, and it needs to be known at compile time. So, 
having an arbitrary default constructor just doesn't work. So, you can't have 
a default constructor on a struct. The result of one design decision (making 
it so that no variables in D are undefined by default) forces another (no 
default constructors for structs).

Declaring a static opCall is the typical way to get around it, and if you need 
it so that you're struct can't be default-initialized, you disable it

@disable this();

which makes it so that that struct has no init value and cannot be used in any 
situation where an init value is required (which carries its own annoyances, 
but it's an option). However, I believe that @disabling this is very broken at 
the moment unfortunately, and it doesn't actually end up disabling much.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list