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

matheus matheus at gmail.com
Tue Oct 25 20:36:28 UTC 2022


On Tuesday, 25 October 2022 at 20:12:25 UTC, Paul Backus wrote:
> On Tuesday, 25 October 2022 at 17:54:16 UTC, Salih Dincer wrote:
>> On Tuesday, 25 October 2022 at 17:18:35 UTC, Paul Backus wrote:
>>> It's not a bug. They're pointing to the exact same instance 
>>> of `A` in memory:
>>
>> I don't understand?  So I don't understand why it causes 
>> problems with dynamic arrays!  So why is there nothing wrong 
>> with the static array in the example below?
>
> Static arrays are value types. When you copy a static array, 
> the copy's data is stored in a separate block of memory from 
> the original:
>
> ```d
> int[1] a = [1];
> int[1] b = a;
>
> assert(&a[0] !is &b[0]); // different memory
> ```
>
> Dynamic arrays are reference types. When you copy a dynamic 
> array, both copies point to the same block of memory:
>
> ```d
> int[] a = [1];
> int[] b = a;
>
> assert(&a[0] is &b[0]); // same memory
> ```
>
> In order to create a copy of a static array with its own block 
> of memory, separate from the original, you have to use the 
> built-in `.dup` method:
>
> ```d
> int[] a = [1];
> int[] b = a.dup;
>
> assert(&a[0] !is &b[0]); // different memory
> ```

This is interesting, I understand the point of "reference vs 
copy", and I'm OK with this design choice of, but I wonder in the 
case of newcomers if this is a case the generate more problem 
understanding this rules, like we are having here.

Matheus.


More information about the Digitalmars-d-learn mailing list