Successively prepending to slices.

monarch_dodra monarchdodra at gmail.com
Wed Apr 9 22:54:49 PDT 2014


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".


More information about the Digitalmars-d-learn mailing list