Defaut initialization of structs

Steven Schveighoffer schveiguy at gmail.com
Tue Oct 14 00:32:04 UTC 2025


On Monday, 13 October 2025 at 14:13:26 UTC, Jonathan M Davis 
wrote:
> And if a struct defines a static opCall which can be called 
> with no arguments, then
>
>     S s;
>     auto s = S.init;
>
> will properly initialize the struct, whereas
>
>     auto s = S();
>
> will do whatever the static opCall does (and there's no 
> guarantee that the static opCall even returns a value let alone 
> that it returns an S). So, in that situation, you almost 
> certainly don't want to be using S() (and if you do, it's 
> because you know exactly what type you're dealing with and how 
> it will behave).

FYI, one thing I learned which actually quite sucks about 
`opCall`, is that this also tries to call *non-static opCall*.

```d
struct S {
    int opCall() => 1;
}

void main() {
    auto s = S(); // error
}
```

Oh, and add a parameter to opCall? Still tries to call it.

It's one wart I wish we could fix. There's a reason why most 
people don't use opCall, it's just hard to deal with.

-Steve


More information about the Digitalmars-d-learn mailing list