Why allow initializers of non-static members that allocate?
Arafel
er.krali at gmail.com
Fri Jun 10 13:28:10 UTC 2022
On 10/6/22 14:58, Salih Dincer wrote:
> On Friday, 10 June 2022 at 07:35:17 UTC, Bastiaan Veelo wrote:
>> I have been foolish enough to make a mistake like this:
>> ```d
>> struct S
>> {
>> int[] arr = new int[](5);
>> }
>> ```
>
> Well, if the b's may not be equal, there's a simple solution. But why
> are a's like that, they're not static!
>
> ```d
> void main()
> {
> struct S(size_t size)
> {
> int[] arr = new int[size];
> }
>
> S!5 a1, a2;
> assert(a1.arr.ptr == a2.arr.ptr);
>
> S!5 b1;
> S!6 b2;
> assert(b1.arr.ptr != b2.arr.ptr);
> }
> ```
> SDB at 79
Because the `arr` are created for each instantiation of the template.
All S!5 share one default value, so you could also:
```d
assert (a1.arr.ptr == b1.arr.ptr);
```
However, S!6 becomes a completely different struct, and thus gets a
different default `arr`.
Note that this would also happen with static members:
```d
struct S(int T) {
static int foo;
}
static assert(&S!1.foo !is &S!2.foo);
void main() { }
```
More information about the Digitalmars-d-learn
mailing list