Disallowing S() when struct S has a constructor

Nick Treleaven nick at geany.org
Thu Aug 29 16:44:46 UTC 2024


```d
struct S
{
     int i;
     this(int);
}

S a = {}; // error, use ctor instead
S b = S(); // fine!
```
Why isn't the last line also disallowed (like `a`'s struct 
initializer) when there's a constructor? If the answer is that 
struct constructors don't need to be called to create a valid 
struct instance, then why disallow the struct initializer?

It's also inconsistent with classes. If you want a default 
initialized literal you can write S.init. There is one difference 
for nested structs, that S() will do runtime initialization of 
the context pointer hidden field.

Allowing S() means we can't diagnose code trying to call a 
variadic constructor with no arguments - it silently fails:

```d
struct S
{
     this(int[]...) { writeln("ctor"); }
}

void main()
{
     S s;
     s = S(); // huh, no ctor call
}
```

Should we make S() for any struct an error in the next edition?


More information about the Digitalmars-d mailing list