Why allow initializers of non-static members that allocate?

Steven Schveighoffer schveiguy at gmail.com
Fri Jun 10 14:56:24 UTC 2022


On 6/10/22 3:46 AM, Mike Parker wrote:
> 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`.

Yes, it can't be done the way that is expected (which is common to many 
languages): allocate one for every instance.

>>
>> 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?"

Here the language is being extremely unsafe.

Not only is the field shared between instances, it's shared across 
instances in *different threads*.

Discovered circa 2009: https://issues.dlang.org/show_bug.cgi?id=2947

It should be illegal to declare a field this way that has mutable 
references without being `shared`. End of story.

-Steve


More information about the Digitalmars-d-learn mailing list