Can someone explain why i can change this immutable variable please?

Ali Çehreli acehreli at yahoo.com
Wed Oct 9 08:33:23 PDT 2013


On 10/09/2013 08:26 AM, Gary Willoughby wrote:
> Can someone explain why i can change Bar's immutable name member please?
>
>      import std.stdio;
>
>      class Foo
>      {
>          public void change(string name)
>          {
>              name = "tess";
>              writeln(name);
>          }
>      }
>
>      class Bar
>      {
>          private static immutable string name = "gary";
>
>          public void test()
>          {
>              auto foo = new Foo();
>              foo.change(this.name);
>          }
>      }
>
>      void main(string[] args)
>      {
>          auto bar = new Bar();
>          bar.test();
>      }
>
> I thought an error would inform me that the `Foo.change` function is
> being called with the wrong parameter type.

Foo.Change receives a string:

     public void change(string name)
     {
         name = "tess";
         writeln(name);
     }

That string is independent from the argument (i.e. Bar.name). They 
initially share the same characters. Either of those strings can leave 
this sharing at will, and that is exactly what name="tess" does. 'name' 
now refers  to different immutable chars.

Ali



More information about the Digitalmars-d-learn mailing list