Successively prepending to slices.

dnspies dspies at ualberta.ca
Thu Apr 10 13:02:46 PDT 2014


On Thursday, 10 April 2014 at 05:54:52 UTC, monarch_dodra wrote:
> On Wednesday, 9 April 2014 at 23:53:04 UTC, dnspies wrote:
>> Does concatenation always create a new array?  What if the 
>> type of the original is immutable (or even const)?  In that 
>> case, wouldn't it be worthwhile to check first if rhs can be 
>> copied to the right of lhs?
>
> Yes, it *always* creates a new array. First:
> The resulting array is guaranteed new. Consider:
> 1. If "rhs" was copied to the right of "lhs", then "lhs" and 
> "result" would be aliasing data:
> a = [1];
> b = [1];
> c = a ~ b;
> c[0] = 2;
> assert(a[0] == 1); //Could fail! A got clobbered!
>
> 2. If "lhs" has some capacity, then it is guaranteed its next 
> concatenation will be non allocating.
> a = [1];
> a.reserve(2);
> p = a.ptr;
> b =a ~ 2; //Uses a's capacity;
> a ~= 2; //relocates.
> assert(a.ptr == p); //Fails!
>
> If you *really* wanted to "make concatenation maybe append", 
> you can do it this way:
> a = [1, 2, 3];
> b = [...];
> c = a; c ~= b; //c has the same contents as "a ~ b", but may 
> actually contain a part of "a".

The aliasing thing isn't a problem if the data-type is const or 
immutable, because you can't change it any way. (Your "A got 
clobbered" example doesn't apply)


More information about the Digitalmars-d-learn mailing list