shallow copy of const(Object)[]
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Nov 2 03:56:52 PST 2014
On Sunday, 2 November 2014 at 00:33:53 UTC, Jonathan M Davis via
Digitalmars-d-learn wrote:
> If you want to make sure that a dynamic array refers to new
> memory and is not
> a slice of another one, then you'd typically use dup or idup,
> and in almost
> all cases, that's exactly what you want. However, you have the
> rather odd case
> of trying to make sure that you end up with a new block of
> memory, but you're
> dealing with an array of const reference types.
[...]
> If you really do need to make a copy of the memory, then you're
> going to need
> to actually end up with const(Object)[], because you can't
> convert
> const(Object) to Object or immutable(Object)[] without doing a
> deep copy
> (which is why dup and idup are failing for you).
The thing that bugs me about dup is that it's documented to
"Create a dynamic array of the same size and copy the contents of
the array into it" [1]. Which would be exactly what I wanted. And
it would be a more basic operation than what it actually does.
> If we had cdup, then that
> would presumably do what you want,
Well, of a cdup I'd expect the result always to be const. I'm
missing an "inoutdup", possibly with opportunistic conversion to
mutable. And I think such behaviour would fit the name "dup"
better (and the current documentation).
> std.array.array _should_ work with that however, since it's
> just allocating an
> array with the same element type as the element type of the
> range that it's
> given (which could be an array). However, it clearly is buggy
> in this case,
Got it. std.array.array should do it.
> pretty much only leaving you with something like I showed you
> before:
>
> const(Object)[] b;
> b.reserve(a);
> foreach(e; a)
> b ~= e;
I actually mentioned that in the OP.
More information about the Digitalmars-d-learn
mailing list