digitalmars.D - Keeping references to dynamic arrays
- brad (42/42) Jul 23 2004 Hi guys, I've just started playing with D again. I'm having a little
Hi guys, I've just started playing with D again. I'm having a little trouble getting my head around Dynamic arrays, especially when the GC gets involved. My basic usage scenario is this, I have multiple classes that want to reference the same large dynamic array. From the small test cases I've written, if the array is resized and needs to be realloc'd to a different place then they don't keep their reference. So... int [] a1; a1.length = 1; int [] a2 = a1; a1.length = 300; // or someother value that moves the array a2[0] = 5; a1[0] = 1; // this is the point where I really want a1[0] == a2[0] Is there a way to do this? It seems to me that this is quite a subtle area, and may possibly introduce bugs. From what I can tell it has the following effects (maybe) - It is never safe to pass C a dynamic array if the library is going to keep that array around. (Note, are there any restrictions on what the GC can do with arrays, ie is it free to move arrays at will for heap compation?) - Even if the C library isn't going to keep the array around, multi-threaded D apps may have bugs due to. 1. int [] a2 = a1[0...4] 2. -- another thread resizes a1 & causes a move 3. a2[0] = 5 // ie, expecting a2 to be an alias of a1 - Does this mean that to have arrays that do allow resizing and move correctly, we need to wrap the array in a class? It just feels to me like you don't really know where you stand with D dynamic arrays. You can't trust to alias them with a pointer, or with an array slice. The only real way to know you are writing to element x in the array is to dereference the original array at position x. My intuitive way that I thought this would work was that all slices or dynamic array assignments would essentially act like a reference to the actual array, in much the same way as assigning objects is by reference. To my point of view this would be much more intuitive and consistant than the current way I think it works. Could I please be enlightened on how all this actually works - rather than how I think it may work? :) Cheers Brad
Jul 23 2004