Should .idup simply do nothing for arrays that are already immutable?

Simen kjaeraas simen.kjaras at gmail.com
Fri Jan 8 15:54:39 PST 2010


On Fri, 08 Jan 2010 22:28:32 +0100, BCS <none at anon.com> wrote:

> Hello dsimcha,
>
>> import std.stdio;
>>  void main() {
>> immutable foo = "FOO";
>> immutable bar = foo.idup;
>> writeln(foo.ptr, '\t', bar.ptr);
>> }
>> Output:
>> 42C090  97AE40
>> Should we define .idup on an already-immutable array to simply do
>> nothing?  It seems that there is never any good reason to copy an
>> immutable array, and it would avoid the need to either needlessly copy
>> an array or explicitly check for immutability in metaprogramming
>> situations.
>>
>
> I can think of one case where I would want to force the copy: In  
> template code where I've got a mutable or immutable object/array and I  
> want to make a modified immutable version of it. - idup it
> - modify it via casting away the immutability
> - never change it again

Don't do this. It's undefined, it's ugly, and it's wrong, and the
language definitely should in no way aid such behavior.

> To do this totally correctly would requiter 2 copies, (original to  
> mutable to immutable). The other option would be to make a mutable copy  
> and then cast it into an immutable object.

The last option is the correct one, IMO. Casting a unique object to
immutable is well-defined and good.

-- 
Simen



More information about the Digitalmars-d mailing list