class - mutable method X.this is not callable using a immutable object error in D -
i have d code copied page: http://ddili.org/ders/d.en/class.html
import std.stdio; struct s { (int x) { this.x = x; } int x; } class foo { s o; char[] s; int i; // ... this(s o, const char[] s, int i) { this.o = o; this.s = s.dup; this.i = i; } foo dup() const { return new foo(o, s, i); } immutable(foo) idup() const { return new immutable(foo)(this.o, this.s, this.i); } } void main() { auto var1 = new foo(s(5), "hello", 42); auto var2 = var1.dup(); immutable(foo) imm = var1.idup(); writeln(var1); writeln(var2); writeln(imm); }
the issue have "mutable method a.foo.this not callable using immutable object" error when compile it.
you're receiving error because called new immutable(foo)(this.o, this.s, this.i);
looks immutable
constructor, , have constructor mutable object defined, default. can solve writing constructor , marking immutable
, must how mark methods const
, there better , easier solution.
try marking constructors , methods pure
if can. if mark constructor pure
, constructor can used both mutable , immutable
objects. alternatively, can mark idup
method pure
, construct new foo
, mutable object, , return immutable
. because pure
functions can safely create immutable data if data returned isn't referenced elsewhere. in other words, uniquely owned memory can moved out immutable
types.
Comments
Post a Comment