当我在D中分配对象时,是否会复制它?
void main() {
auto test = new Test(new Object());
tset.obj;
}
class Test {
public Object obj;
public this(Object ref origObj) {
obj = origObj; // Will this copy origObj into obj, or will origObj and obj point to the same data? (Is this a valid way to pass ownership without copying the object?)
}
}
答案 0 :(得分:5)
仅复制引用,对象本身不会重复。您可以使用.dup
显式复制对象。
答案 1 :(得分:3)
类是引用类型,所以当你有
时Object o;
o
是对Object
而非实际Object
的引用,因此复制它只会复制引用。就像指针一样。
auto a = new int;
*a = 5;
auto b = a;
assert(a is b);
assert(*a == *b);
*b = 5;
assert(*a == 5);
我建议阅读Andrei Alexandrescu的The D Programming Language或者AliÇehreli的D Programming Language Tutorial。特别是,Ali的书中this chapter讨论了类,包括如何分配和复制它们。