Is "auto t=T();" not the same as "T t;"?

Andrey Zherikov andrey.zherikov at gmail.com
Tue Oct 25 15:50:46 UTC 2022


On Tuesday, 25 October 2022 at 14:53:50 UTC, Adam D Ruppe wrote:
> But just don't do this. Only basic values and immutable strings 
> are good to initialize this way. With the array or class 
> objects, you're liable to get some shared thing.
>
> If you change this to be initialized in a constructor (which 
> will require an argument in D) or factory function, you'll get 
> far more consistent behavior as each instance will have its own 
> array.

I'd like to tune default ctor but structs can't have custom one.
Adding a ctor with parameter seems a hack to me - and compiler 
still allows default construction even when default ctor is 
disabled:

```d
struct A
{
     int[] i;
}
struct B
{
     A[] a;
     @disable this();
     this(bool)
     {
	    A[] a = [A.init];
     }
}
void main()
{
     auto b1 = B.init;
     b1.a[0].i ~= 1;
     b1.a ~= A.init;
     b1.a[0].i ~= 11;
     b1.a[1].i ~= 12;
     b1.writeln;

     auto b2 = B.init;
     b2.writeln;
}
```
This fails in run time, not compile time:
```
core.exception.ArrayIndexError at onlineapp.d(19): index [0] is out 
of bounds for array of length 0
----------------
??:? _d_arraybounds_indexp [0x55b558b8ec55]
./onlineapp.d:19 _Dmain [0x55b558b6bd5f]
```

> As for why B() and B.init are different here... i don't know, 
> probably some subtly of the compiler's implementation.

Actually `auto b = B.init;` behaves the same way as `auto b = 
B();` but they don't do the same as `B b;`


More information about the Digitalmars-d-learn mailing list