deep copy or shallow copy?

Jonathan M Davis jmdavisProg at gmx.com
Fri Dec 9 14:58:03 PST 2011


On Friday, December 09, 2011 14:33:38 Ali Çehreli wrote:
> On 12/09/2011 01:18 PM, Jonathan M Davis wrote:
> > On Friday, December 09, 2011 22:09:15 Timon Gehr wrote:
> >> On 12/09/2011 09:32 PM, Ali Çehreli wrote:
> >>> So it is impossible to do anything shallow with them unless we
> >>> explicitly maintain a pointer to a fixed-length array ourselves.
> >>> 
> >>> Ali
> >> 
> >> You can always slice it, of course
> >> 
> >> int[3] a;
> >> int[] b = a[]; // b now is a dynamic array that aliases a's contents
> > 
> > Though, of course, you have to be careful with that, since the static
> 
> array
> 
> > then owns the memory for that dynamic array, and if the static array
> 
> goes out
> 
> > of scope before the dynamic array does, then the dynamic array points
> > to
> > garbage and will result in bugs.
> > 
> > - Jonathan M Davis
> 
> That's news to me. Don't the static array elements belong to the
> runtime, managed by the garbage collector, and will be kept alive as
> long as the slice is alive?

Goodness no. The static array is on the stack, not on the heap. If you append 
to a dynamic array which refers to a static array, then it'll reallocate that 
memory onto the heap (leaving the original static array alone) so that the 
dynamic array is then managed by the runtime, but the static array never is, 
since it's on the stack, and as long as the dynamic array is a slice of the 
static array, it's going to be pointing to the wrong thing if the static array 
leaves scope.

So, slicing a static array to pass it to a function which isn't going to keep 
the memory around isn't a big deal, but doing something like

int[] func()
{
 int[5] a;
 return a[];
}

is as bad as

int* func()
{
 int a;
 return &a;
}

though at least in the second case, the compiler will give you an error. The 
first probably should as well, but it doesn't currently. It _is_ escaping a 
reference to a local variable though, which is a bug.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list