Why allow initializers of non-static members that allocate?

matheus matheus at gmail.com
Sat Jun 11 02:22:28 UTC 2022


On Saturday, 11 June 2022 at 01:52:58 UTC, Mike Parker wrote:
> ...
> That's because static arrays are allocated as part of the 
> instance:
> ...

Yes I understood the problem, but the naive me was thinking that 
in this example:

struct S{
     int[] arr = new int[](5);
}

For some reason this would be transformed as a statically "int[5] 
arr" in the case of structs.

But now I see that's not the case and "arr" points to whatever 
was allocated by "new", and will share across the instances of S 
(Since it's the same address).

> ... So would you then really want a warning every time you 
> initialize a static array field?

Well would this be annoying? Yes, mainly if I already know this, 
but if not, then it would be like a nice to know warning for 
newbies like myself. By the way this would be only in the cases 
that a static array field being initialized with dynamic 
allocation like in the case of struct declaration, not on every 
place.

> ...
> So the question in each case would be, where's the line between 
> helpful and annoying?

Well I like to think about this like the "-Wall" flag in C 
compilers, you need to go for it, and you just dismiss the 
warning in such case if you don't agree or know what you're doing.

> ...
> The compiler should be as helpful as it can, but it has to be 
> helpful without getting in the way. There's a significant 
> amount of learning by trial and error in any programming 
> language. So I think there has to be a distinction between 
> things like "easy to do by accident even when you know the 
> deal"  and "once you learn it, you're unlikely to do it again".

Yes no doubt about it, by the way like I said, I never used this 
form to initialize fields in structs, I always used the "T[n] 
member", but in this particular case the result would have been 
very different from what I expected.

Anyway I'm always lurking around this Forum and learning new 
things.

Thanks,

Matheus.

PS: I'm ESL so sorry for my English mistakes.


More information about the Digitalmars-d-learn mailing list