no-arg constructor for structs (again)

deadalnix deadalnix at gmail.com
Thu Sep 20 02:58:30 PDT 2012


Le 20/09/2012 08:26, monarch_dodra a écrit :
> On Wednesday, 19 September 2012 at 12:31:08 UTC, Maxim Fomin wrote:
>> On Wednesday, 19 September 2012 at 11:51:13 UTC, monarch_dodra wrote:
>>> The biggest issue with not having a no-arg constructor can easilly be
>>> seen if you have ever worked with a "Reference Semantic" semantic
>>> struct: A struct that has a pointer to a payload. Basically, a class,
>>> but without the inherited Object polymorphism.
>>
>> This means that you still have a class object. What is design behind
>> inserting class into the structure for the sake of escaping from classes?
>>
>
> That's not the point at all. For starters, the "Payload" is another
> struct, NOT a class wrapped in a struct.
>
> As for why we aren't using a class to begin with? First, because a class
> wraps much more than we want: polymorphism, adherence to a base "Object
> Type", virtual opEquals, RTTI...
>
> But mostly, because the object we manipulate is a struct and has always
> been a struct. It uses reference semantics, but is in dire need of a an
> initialization to default.
>
> On Wednesday, 19 September 2012 at 14:09:10 UTC, deadalnix wrote:
>> Le 19/09/2012 15:24, Timon Gehr a écrit :
>>> I don't think making the use of optional parens affect semantics is an
>>> idea worth following.
>>
>> I have to agree with that.
>>
>> However, argument-less constructor is something required for struct.
>> The problem is raised on a regular basis on this newsgroup, and some
>> solution already have been proposed.
>>
>> As discussed earlier in the reference thread, the compiler will have
>> to track down initialization at some point. A struct with an
>> argument-less constructor which isn't initialized must be an error.
>> This will avoid the () semantic dichotomy while solving that problem.
> Would you happen to have some links to those proposed solutions, or
> reword them here for us?

My solution was to include code analysis in the compiler in order to 
ensure that a struct with an argument-less constructor is assigned 
before being used.

struct S {
     this() {}
}

S s;
foo(s); // Error, s may not have been initialized

s = S();
foo(s); // OK

S.init contains the struct memory layout as it is before any constructor 
run on them. It is not @safe to use in on a struct with a default argument.

Note that the code analysis required for such a task is planed to be 
included in dmd, to support @disable this(); anyway.


More information about the Digitalmars-d mailing list