Is "auto t=T();" not the same as "T t;"?
Paul Backus
snarwin at gmail.com
Tue Oct 25 17:18:35 UTC 2022
On Tuesday, 25 October 2022 at 16:52:48 UTC, Salih Dincer wrote:
> On Tuesday, 25 October 2022 at 13:51:30 UTC, Andrey Zherikov
> wrote:
>> Does the second piece of code shows a bug or my expectation is
>> not correct (and why if so)?
>
> This is a bug:
>
> ```d
> void main()
> {
> struct B
> {
> struct A
> {
> int i = 10;
> }
> A[] a = [A.init];
> }
>
> B[2] b;
> assert(b[0].a[0].i == 10);
> assert(b[1].a[0].i == 10);
>
> b[0].a[0].i = 1;
> assert(b[0].a[0].i == 1); // ok...
> assert(b[1].a[0].i == 1); // must be 10 !!!
> }
> ```
It's not a bug. They're pointing to the exact same instance of
`A` in memory:
```d
void main()
{
struct B
{
struct A
{
int i = 10;
}
A[] a = [A.init];
}
B[2] b;
assert(b[0].a.ptr is b[1].a.ptr);
}
```
As explained in [Adam's reply][1], what happens here is that
there is a single, global `A[]` allocated at compile time, which
is shared between all instances of `B.init`. It's the same as if
you'd written
```d
struct B
{
struct A
{
int i = 10;
}
static A[] globalArray = [A.init];
A[] a = globalArray;
}
```
[1]:
https://forum.dlang.org/post/yznhocajstphrozpnqzo@forum.dlang.org
More information about the Digitalmars-d-learn
mailing list