Can someone explain why i can change this immutable variable please?
Orvid King
blah38621 at gmail.com
Wed Oct 9 08:35:06 PDT 2013
On Wednesday, 9 October 2013 at 15:26:35 UTC, 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.
This would fail if you were to declare `change` as `void
change(ref string name)`. This is valid because you are passing
the value of a reference to a string. `Bar.name` is an immutable
reference to a string, but your only passing a copy of that
reference to `Foo.change`, that copy is mutable by default.
More information about the Digitalmars-d-learn
mailing list