shallow copy of const(Object)[]
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Nov 1 03:30:05 PDT 2014
On Saturday, 1 November 2014 at 00:08:23 UTC, Jonathan M Davis
via Digitalmars-d-learn wrote:
> So, by shallow copy, you mean that you want an array that
> contains the same
> elements but is a new array?
yes
> If that's what you want, just slice the array.
>
> auto b = a[];
This is the same as `auto b = a;`.
> Sure, they'll point to the same spot in memory still, but
> because all of the
> elements are const, you can't mutate them, so it really doesn't
> matter. All it
> affects is that because both arrays have the same block of
> memory after them,
> appending to one of them would make it so that appending to the
> other would
> force it to reallocate. For for most intents and purposes, you
> essentially
> have two different arrays.
Except I don't. The elements are not immutable, so they may be
pulled from under my feet from elsewhere. And more importantly,
`a` may refer to non-GC memory. Like the stack, for example:
class C
{
const(Object)[] objects;
this(const(Object)[] objects ...)
{
this.objects = objects;
}
}
C f()
{
return new C(new Object);
}
void main()
{
auto c = f();
auto o = c.objects[0];
f(); /* writing over the previous array */
assert(o is c.objects[0]); /* fails */
}
More information about the Digitalmars-d-learn
mailing list