struct and default constructor

deadalnix deadalnix at gmail.com
Sun Nov 27 11:53:46 PST 2011


Hi,

I wonder why struct can't have a default constructor. TDPL state that it 
is required to allow every types to have a constant .init .

That is true, however not suffiscient. A struct can has a void[constant] 
as a member and this doesn't have a .init . So this limitation does not 
ensure that the benefit claimed is garanteed.

Additionnaly, if it is the only benefit, this is pretty thin compared to 
the drawback of not having a default constructor.

We already have @disable this(); for structs. This cause the struct to 
behave differently and cause the error « initializer required for type 
xxx » when a variable of type xxx is defined without initialization. 
This doesn't prevent the struct to get a constant .init and to use it 
(even if this .init is probably garbage in this case, the whole point of 
the @disable is to force the user to use a constructor or to copy).

The whole stuff seems very unclear and limitations arbitrary.

Note that a static opCall and a @disabel default constructor doesn't do 
the trick as opCall can't be used with new to allocate on the heap. This 
is only a cheap workaround.

Note also that xxx myvar = xxx.init; worls and doesn't trigger postblit. 
So the @disable this(); is also a structure thatd oesn't garantee anything.

The point of classes and struct beeing different in D is slicing. 
Default constructor is unrelated to that problem.

Why not allow both @disable this(); and default constructor construct, 
both triggering the error « initializer required for type xxx » ? This 
would make much more sense. Postblit should also be triggered on 
assiagnation with .init to ensure the consistency of the whole construct.


More information about the Digitalmars-d mailing list