What is the case against a struct post-blit default constructor?

Malte Skarupke malteskarupke at web.de
Mon Oct 8 09:47:43 PDT 2012


So this has been brought up many times 
(http://www.digitalmars.com/d/archives/digitalmars/D/Struct_no-arg_constructor_173172.html 
http://www.digitalmars.com/d/archives/digitalmars/D/learn/Default_constructor_for_structs_20997.html 
http://www.digitalmars.com/d/archives/digitalmars/D/struct_and_default_constructor_150016.html)

However there was never a good answer.

I would like a struct default constructor. My expected behavior 
for it is that the struct gets initialized to .init, then my 
destructor gets called so that I can do additional things if I 
want.
This destructor always gets called when my struct is created 
without arguments.

So for example

struct S
{
     this()
     {
         assert(bar == 10);
         foo = [5].ptr;
     }
     int * foo;
     int bar = 10;
}
S s;
assert(*s.foo == 5);

Possible cases against it:
- "It would be slower than just initializing to .init." My 
proposed solution: Make the default constructor optional. If I 
have a struct that doesn't define a default constructor, it is 
just intialized to .init. So I can have the speed if I want to. 
Also always run it post-blit (blitted from .init). Meaning I only 
need to use it for things that can only be initialized at runtime.
- "There already is a solution in @disable this(); static 
opCall() {...}." This is hacky and working against the language. 
It also makes it so that you can not allocate your struct on the 
heap.
- "Structs should be simple." I haven't heard this argument, but 
I could imagine someone making it. I think structs should not be 
simple. They are much too useful for that. Also them having copy 
constructors and opAssign indicates that structs aren't expected 
to be simple.
- "There would be a way around it by doing S s = S.init;" I don't 
think that's a problem. If users want to shoot themselves in the 
foot, let em. The important part is that they have to go out of 
their way to do it. You could also handle that case in the copy 
constructor or assignment operator. (which is an improvement to 
the current behavior where you have to handle that case in every 
single member function, see for example std.typecons.RefCounted)


So I really can't think of a reason for why you wouldn't want 
this. Yet this discussion has happened several times already. 
There is clear demand for it and very good reasons, such as those 
mentioned in all the linked discussions.

So why is this being rejected?

Cheers,
Malte


More information about the Digitalmars-d mailing list