Copying array with const correctness
Vindex9
tech.vindex at gmail.com
Tue Oct 7 19:07:28 UTC 2025
I’d like to clarify: the original goal was to create an
alternative to Dub in order to make copies of arrays of objects
that contain copying constructors.
It's all good like this:
```d
unittest
{
T[] copyArray(T)(const T[] arr) if (!is(T == class)) {
T[] copy = new T[arr.length];
for (size_t i = 0; i < arr.length; i++) {
// it doesn't work with postblit, only with modern
copy ctor
T elem = arr[i];
copy[i] = elem;
}
return copy;
}
struct S {
int x, y;
bool[] a;
this(ref return scope const S rhs) {
this.x = rhs.x;
this.y = rhs.y;
this.a = rhs.a.dup;
}
}
const S[] arr = [
S(1, 2, [true, false]),
S(3, 4, [false, true])
];
// S[] copy = arr.dup; // It can't be compiled!
S[] copy = copyArray(arr); // from const array to non-const
one
assert(copy.length == arr.length);
for (size_t i = 0; i < arr.length; i++) {
assert(arr[i].x == copy[i].x);
assert(arr[i].y == copy[i].y);
assert(arr[i].a == copy[i].a);
assert(arr[i].a.ptr != copy[i].a.ptr);
}
const S[] emptyArr = [];
assert(emptyArr.ptr == null);
S[] emptyCopy = copyArray(emptyArr);
assert(emptyCopy.ptr == null);
}
```
The problems started when I decided to increase the versatility.
More information about the Digitalmars-d-learn
mailing list