Copying with immutable arrays

Don Clugston dac at nospam.com
Tue Oct 30 04:02:13 PDT 2012


On 29/10/12 07:19, Ali Çehreli wrote:
> On 10/28/2012 02:37 AM, Tobias Pankrath wrote:
>  > the struct
>  > SwA from above does neither correspond to SA nor to SB, it's imo more
>  > like SC:
>  >
>  > struct SC {
>  > immutable(int)* i;
>  > }
>
> Just to confirm, the above indeed works:
>
> struct SC {
>      immutable(int)* i;
> }
>
> void main()
> {
>      immutable(SC)[] arr1;
>      SC[] arr2 = arr1.dup;    // compiles
> }
>
>  > Now a copy would do no harm, everything that was immutable in the source
>  > and is still accessable from the copy is immutable, too. Any reason
>  > (despite of implemenational issues) that this is not how it works?
>
> Getting back to the original code, the issue boils down to whether we
> can copy imutable(string[]) to string[]:
>
> import std.stdio;
>
> struct SwA {
>      string[] strings;
> }
>
> void main()
> {
>      immutable(SwA)[] arr1;
>      writeln(typeid(arr1[0].strings));
> }
>
> The program prints the following:
>
> immutable(immutable(immutable(char)[])[])
>
> Translating the innermost definition as string:
>
> immutable(immutable(string)[])
>
> Let's remove the struct and look at a variable the same type as the member:
>
>      immutable(string[]) imm = [ "a", "b" ];
>      writeln(typeid(imm));
>
> The typeid is the same:
>
> immutable(immutable(immutable(char)[])[])
>
> So we can concentrate on 'imm' for this exercise. This is the same
> compilation error:
>
>      immutable(string[]) imm = [ "aaa", "bbb" ];
>      string[] mut = imm;       // <-- compilation ERROR
>
> If that compiled, then both 'imm' and 'mut' would be providing access to
> the same set of strings. But the problem is, 'mut' could replace those
> strings (note that it could not modify the characters of those strings,
> but it could replace the whole string):
>
>      mut[0] = "hello";
>
> That would effect 'imm' as well. ('imm' is the equivalent of SwA.strings
> from your original code.)
>
> Ali

Awesome answer, it's these kinds of responses that make the D community 
so great.





More information about the Digitalmars-d-learn mailing list