我从这个页面复制了这个D代码:http://ddili.org/ders/d.en/class.html
import std.stdio;
struct S {
this (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);
}
问题是我在编译时有“可变方法a.Foo.this不能使用不可变对象调用”错误。
您收到此错误是因为您调用了new immutable(Foo)(this.o, this.s, this.i);
这会查找一个immutable
构造函数,并且您只有一个构造函数用于定义可变对象,这是默认值。你可以通过编写一个构造函数并将其标记为immutable
来解决这个问题,就像你将方法标记为const
一样,但是有更好的,通常更容易的解决方案。
如果可以的话,尝试将构造函数和方法标记为pure
。如果将构造函数标记为pure
,则构造函数可用于mutable和immutable
对象。或者,您可以将idup
方法标记为pure
,构造一个new Foo
,这是一个可变对象,并将其作为immutable
返回。这都是因为如果返回的数据未在别处引用,pure
函数可以安全地创建不可变数据。换句话说,唯一拥有的内存可以移出到immutable
类型。