Reputation: 2162
How do I create a reference to immutable classes, but while keeping the ability to reassign the reference, sort of like string
?
import std.stdio;
immutable class Test {
string test(){
return "test";
}
}
void main(){
auto test = new Test;
writeln(test.test);
}
This causes an error, because the created instance is not immutable:
test.d(14): Error: immutable method test.Test.test is not callable using a mutable object
new immutable
doesn't work either, because the resulting variable cannot be assigned a new one afterwards.
immutable(Test)*
would work, but is there a way avoiding pointers?
Upvotes: 2
Views: 76
Reputation: 25605
Use std.typecons.Rebindable http://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;
Upvotes: 4
Reputation: 843
You can use immutable
in the same way of auto
to infer types:
immutable test = new Test;
immutable other_test = test;
Upvotes: 0