static array internal & dangling reference

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 12 05:11:02 PST 2016


On Saturday, 12 November 2016 at 12:16:02 UTC, Andrew wrote:

>>
>> Bear in mind that static arrays are implicitly sliced when 
>> passed to or returned from a function anywhere a dynamic array 
>> is expected. If you modify f() to look like this:
>>
>> int[] f()
>> {
>>   int[10] sa;
>>   foreach(int i, ref sa_i;sa){
>>     sa_i=i;
>>   }
>>   return sa;
>> }
>>
>
> I thought that if you changed the function signature to int[10] 
> f() to return a static array, this should be returned by value, 
> and so should be safe to use, but it seems that this too points 
> to the same memory.

If the return type is declared as int[10], then yes, returning sa 
should copy all 10 elements in the return. I just verified what 
you said and also found that both have the same address. However, 
if you stomp the stack and then access any value from the array, 
you'll find that it's valid. When returning int[], this is not 
the case. This looks to me like an optimization by the compiler 
to avoid the copy, but I know nothing of the implementation 
details.

And for clarity, I think we should be careful with the term 'by 
value', as dynamic arrays are passed around by value, not by 
reference, just without the members being copied around. Keep in 
mind that a dynamic array is a length and a pointer. Those are 
not passed by reference, but by value. So that this:

void func1(int[] foo) { foo ~= 10; }

And this:

void func2(int[] foo) { foo ~= 10; }

Are not the same. func1 appends to the local slice, meaning it is 
no longer connected to the original that was passed in. func2 
appends to the original array.

>
> To make it safe, should I be using:
>
> auto sb = f().dup;

Yes, if you intend to keep the contents around indefinitely, this 
is the proper way to do it. My point in my previous post was just 
demonstrating that sb remains valid as long as its stack memory 
has not yet been overwritten and, as long as it is made use of 
immediately, nothing is going to break.



More information about the Digitalmars-d-learn mailing list