Why allow initializers of non-static members that allocate?

Mike Parker aldacron at gmail.com
Fri Jun 10 07:46:36 UTC 2022


On Friday, 10 June 2022 at 07:35:17 UTC, Bastiaan Veelo wrote:

> Is there a use case where this makes sense? I would have much 
> appreciated the compiler slapping me on the fingers, but it 
> doesn't. I understand that it is safe and that the compiler can 
> allow this, but why would anyone want that? D-scanner does not 
> check for this either.

Any initialization of a member field is overriding the field's 
`.init` value for the type. If a dynamic allocation set a 
different value per instance, then you'd have inconsistent 
behavior with, e.g., `int a = 5`.


>
> I think a helpful error message would be: "Error: The 
> initializer `A(5)` allocates memory that is shared among all 
> instances of `S`. If you want that, make `S.a` `static`."

I understand that it's not something that people expect, but 
making it an error can't be the answer. And making it a static 
field is not the same thing.

I think this is a case where having a warning that's on by 
default, and which can be explicitly disabled, is useful. "Blah 
blah .init blah blah. See link-to-something-in-docs. Is this what 
you intended?"


More information about the Digitalmars-d-learn mailing list