Disallowing S() when struct S has a constructor

Paul Backus snarwin at gmail.com
Fri Aug 30 17:54:23 UTC 2024


On Friday, 30 August 2024 at 16:58:25 UTC, Ogi wrote:
> On Friday, 30 August 2024 at 15:17:06 UTC, Steven Schveighoffer 
> wrote:
>> I have a bold suggestion instead -- let's just start having 
>> default constructors.
>>
>> What's stopping us? We are on the cusp of ridding ourselves of 
>> magic runtime hooks, they are all now becoming templates.
>>
>> For instance, setting the length of an array now calls a 
>> template and that template could just call the default 
>> constructor if it exists.
>
> I have a much less radical 
> [proposal](https://forum.dlang.org/thread/ekskxgqdyyajbagnxfer@forum.dlang.org). A struct with a default constructor can only be initialized by a constructor call, just like a struct with a disabled default constructor.

There is currently one situation in the D language where `S()` 
and `S.init` have different results: when `S` is a nested struct 
(that is, defined inside a function).

In this situation, `S()` produces an instance with its context 
pointer properly initialized to point to the enclosing stack 
frame, and `S.init` produces an instance with its context pointer 
set to `null`.

This is, for all intents and purposes, a (compiler-generated) 
default constructor. Additional code is executed at runtime when 
you use `S()` instead of `S.init`.

Furthermore, if you use default initialization with one of these 
structs, it behaves like `S()`, not `S.init`:

     void main()
     {
         int n;
         struct S
         {
             void fun() { ++n; }
         }

         S s;
         assert(s is S());
         assert(s !is S.init);
     }

For the sake of consistency, if we allow user-defined default 
constructors for structs, they should behave the same way.


More information about the Digitalmars-d mailing list