.dup vs operation on all elements

faissaloo faissaloo at gmail.com
Mon Dec 3 21:27:52 UTC 2018


On Monday, 3 December 2018 at 20:37:22 UTC, Jonathan M Davis 
wrote:
> On Monday, December 3, 2018 1:07:24 PM MST Goksan via 
> Digitalmars-d-learn wrote:
>> Are there any differences between these 2 methods of copying 
>> elements?
>>
>> double[] array = [ 1, 20, 2, 30, 7, 11 ];
>>
>> // Non dup
>> double[6] bracket_syntax_dup = array;
>> bracket_syntax_dup[] = array;
>> bracket_syntax_dup[0] = 50;
>>
>> // Dup
>> double[6] normal_dup = array.dup;
>> normal_dup[0] = 100;
>>
>> OUTPUT: (array, bracket_syntax_dup and normal_dup 
>> respectively):
>> [1, 20, 2, 30, 7, 11]
>> [50, 20, 2, 30, 7, 11]
>> [100, 20, 2, 30, 7, 11]
>
> dup allocates a new dynamic array and copies the elements of 
> the existing dynamic array to the new one. Calling dup in order 
> to assign to a static array is just needlessly allocating a 
> dynamic array. The contents of the array are going to be copied 
> to the static array regardless, but instead of just copying the 
> elements, if you use dup, you're allocating a new dynamic 
> array, copying the elements into that dynamic array, and then 
> you're copying the elements into the static array. There's no 
> point.
>
> You use dup when you want to copy the elements of a dynamic 
> array instead of simply slicing it. Slicing gives you a new 
> dynamic array that points to exactly the same elements. It's 
> just copying the pointer and the length (meaning that mutating 
> the elements of the new slice will affect the elements in the 
> original array), whereas dup actually allocates a new block of 
> memory for the new dynamic array to be a slice of (copying the 
> elements over in the process), so mutating the elements in the 
> new dynamic array then won't affect the elements in the 
> original.
>
> Regardless, when you create a static array, it's not a slice of 
> anything (since its elements sit directly on the stack), and 
> when assign to it, you're simply copying the elements over.
>
> - Jonathan M Davis

Then shouldn't the following output false, false, true?
import std.stdio;

   class Programmer
   {
       bool is_confused = false;

       void setConfusion(bool confusion_status)
       {
           is_confused = confusion_status;
       }
   }

   void main()
   {
       Programmer[6] array = new Programmer();

       Programmer[6] bracket_syntax_dup = array;
       bracket_syntax_dup[] = array;

       Programmer[6] normal_dup = array.dup;

       normal_dup[0].setConfusion(true);
       bracket_syntax_dup[0] = new Programmer();

       writeln(array[0].is_confused);
       writeln(bracket_syntax_dup[0].is_confused);
       writeln(normal_dup[0].is_confused);
   }



More information about the Digitalmars-d-learn mailing list