Small suggestion for default constructors

Paul Backus snarwin at gmail.com
Thu Jan 19 18:12:03 UTC 2023


On Tuesday, 17 January 2023 at 03:02:46 UTC, Mike Parker wrote:
> On Tuesday, 17 January 2023 at 02:45:30 UTC, TheZipCreator 
> wrote:
>
>> For structs, it automatically generates a constructor, and it'd
>
> There's a distinction. The default initializer for a struct is 
> the `.init` value of each member. `T()` is not a default 
> constructor, but a struct literal that's equivalent to `T.init`.

Almost. There is one situation where `T.init` and `T()` are 
different, and that's when `T` is a nested struct.

```d
void main()
{
     int n;
     struct S
     {
         int fun() { return ++n; }
     }
     auto s1 = S();
     assert(s1.fun() == 1); // ok
     auto s2 = S.init;
     assert(s2.fun() == 2); // segmentation fault
}
```

In the above code, using `S()` initializes `s1`'s context pointer 
at runtime to point to `main`'s stack frame, allowing `s1.fun` to 
access the variable `n`. Using `S.init` to initialize `s2`, 
however, sets the context pointer to `null`, so when `s2.fun` is 
called, the program crashes.


More information about the Digitalmars-d mailing list