shared arrray problem

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 19 13:26:17 PST 2016



On 11/19/2016 11:10 AM, Nicolas Gurrola via Digitalmars-d-learn wrote:
> On Saturday, 19 November 2016 at 18:51:05 UTC, Charles Hixson wrote:
>
>> ubyte[]    header()        @property {    return fHead[4..$];    }
>
> This method should do what you want. You are only returning a slice of 
> the fHead array, so if the caller modifies the length it will only 
> affect of the return value, and not the length of fHead itself.
>
It's worse than that, if they modify the length the array may be 
reallocated in RAM so that the pointers held by the containing class do 
not point to the changed values.  (Read the header comments...it's not 
nice at all.)
More, the class explicitly requires the array to be a particular length 
as it needs to fit into a spot in a binary file, so I really want to 
forbid any replacement of the array for any reason.  The first four 
bytes are managed by the class and returned via alternate routines which 
do not allow the original values to be altered, and this is necessary.  
I could make them immutable, but actually what I do is return, e.g., an 
int of 256 * fHead[0] + fHead[1], which is the length of the header.  
It's an int to allow negative values to be returned in case of error.

So what I'll probably eventually decide on is some variation of 
saveToHead, e.g.:
     bool    saveToHeader    (ubyte[] rec)
     {  if    (rec.length + 4 > dheader)    return    false;
         fHead[4..recLen + 4] = rec[0..$];
         return    true;
     }
unless I can think of something better.  Actually for this particular 
case that's not a bad approach, but for the larger problem it's a lousy 
kludge.


More information about the Digitalmars-d-learn mailing list