shallow copy of const(Object)[]

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 3 05:42:04 PST 2014


On 10/31/14 2:38 PM, anonymous wrote:
> I have a const(Object)[] and I want a shallow copy of the array.
> ..dup doesn't do it, which I thought a bug, but according to
> Martin Nowak it's by design [1].
> std.array.array fails, too. Is there really nothing in phobos for
> this?
>
> static import std.array;
> void main()
> {
>       const(Object)[] a;
>
>       version(dup) auto b = a.dup;
>       /* Nope. Apparently, dup is supposed to convert the elements
> to mutable [1],
>       which doesn't work with const(Object), of course. */
>
>       version(array) auto c = std.array.array(a);
>       /* Nope. Tries to convert to mutable, too? */
>
>       version(meh)
>       {
>           typeof(a) d;
>           d.reserve(a.length);
>           foreach(e; a) d ~= e;
>       }
> }
>
> [1]
> https://github.com/D-Programming-Language/druntime/pull/1001#discussion_r19674927
>

Well, it's a matter of how you look at it when you request "dup". 
Traditionally in D, dup has meant "give me a copy with all the elements 
being mutable". If we were forward thinkers, we would have called this 
'mdup'.

We don't have a way to say "give me a copy and keep all the attributes 
the same".

I think in order to get what you want, we need a new method. I would 
propose one that is pure, and can be deduced to have the result be 
unique, and therefore implicitly castable to any constancy.

What I like about that is:

1. It works with any change of constancy that would normally be allowed.
2. It works with const -> const, which is what we don't currently have 
(cdup)

I think if you change the name (an unfortunate requirement), and then 
add pure and inout appropriately, we have something that may supplant 
dup as the main mechanism to copy arrays.

I think we need 2 overloads. One that takes a const array and returns a 
mutable one, when no indirections are in the elements, and one that 
takes an inout array and returns an inout one for indirections. Both 
should be pure.

-Steve


More information about the Digitalmars-d-learn mailing list