Allow this() { } for structs

IGotD- nise at
Fri Nov 6 15:53:44 UTC 2020

On Friday, 6 November 2020 at 09:54:23 UTC, FeepingCreature wrote:
> On Monday, 2 November 2020 at 19:53:31 UTC, Q. Schroll wrote:
>> Can we just allow this() when the body is essentially empty 
>> (that is: after rewrites and lowerings contains no 
>> statements)? The compiler would happily accept the code and 
>> pretend this() { } isn't there. It would even reduce confusion 
>> because S() is legal as an expression, but this() isn't as a 
>> constructor. With that, this() is legal as a constructor, but 
>> it must not do anything.
> I just want this() always, even with a non-empty body.
> We run into an issue where we need predictable destructor calls 
> for a struct constructed for a with(), but we also want 
> possibly immutable data in the struct, so we *have* to use 
> this() rather than static opCall() which is the standard 
> workaround.
> So we end up with code like this:
> struct StructType {
>   this(int) { ... }
> }
> StructType structType() { return StructType(0); }
> I do not understand what purpose the lack of this() serves. I 
> mean, I understand what purpose it serves, it's so T.init is 
> always equivalent to T(), but I don't understand what purpose 
> *that* serves. T.init is *already* not a valid constructed T if 
> you want to use any invariants and/or call any methods at all. 
> We *already* can't treat them equivalently regardless, so from 
> my perspective the ban on T() serves no purpose.

It's been discussed before and it has been rejected, because some 
motivation based on compiler internals rather than the 
convenience of the programmer. The whole point of a computer 
language is that it is supposed to convenient for humans and not 
the other way around.

Also, I don't see the point why we couldn't hack in support for a 
constructor without any arguments. We already have support for a 
constructor with arguments so I don't understand why without any 
would be impossible to implement.

It's is highly inconvenient and instead I have to use an 
additional init() method with no argument but when I have 
arguments I can use the constructor directly. This really makes 
the language inconsistent.

More information about the Digitalmars-d mailing list