如何创建对不可变 class 的可重新分配引用?

How to create a re-assignable reference to an immutable class?

如何创建对不可变 类 的引用,同时保持重新分配引用的能力,有点像 string?

import std.stdio;

immutable class Test {
    string test(){
        return "test";
    }
}

void main(){
    auto test = new Test;
    writeln(test.test);
}

这会导致错误,因为创建的实例不是不可变的:

test.d(14): Error: immutable method test.Test.test is not callable using a mutable object

new immutable 也不行,因为生成的变量之后不能再赋新的。

immutable(Test)* 可以,但是有没有办法避免指针?

你可以像auto一样使用immutable来推断类型:

immutable test       = new Test;
immutable other_test = test; 

使用std.typecons.Rebindablehttp://dpldocs.info/experimental-docs/std.typecons.Rebindable.html#examples

import std.typecons;
class Widget { int x; int y() const { return x; } }
auto a = Rebindable!(const Widget)(new Widget);
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// Fine
a = new Widget;