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

dsimcha dsimcha at yahoo.com
Fri Jan 8 13:33:14 PST 2010


== Quote from BCS (none at anon.com)'s article
> 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
> 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.

I think the latter is the better way to do this.  Modifying data for which
immutability has been cast away is technically undefined behavior, meaning that
the compiler could, if it wanted to, optimize your code in such a way (via
constant folding, caching, etc.) that your modifications to the immutable data are
never seen by some parts of the code.

Casting mutable data to immutable is well-defined as long as you don't leave any
mutable references to it.



More information about the Digitalmars-d mailing list