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

Gary Willoughby dev at nomad.so
Wed Oct 9 08:46:28 PDT 2013


On Wednesday, 9 October 2013 at 15:33:23 UTC, Ali Çehreli wrote:
> 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

So why does this give me an error i expect:

	import std.stdio;

	class Foo
	{
		public void change(string[] name)
		{
			name[0] = "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();
	}


More information about the Digitalmars-d-learn mailing list