将对象复制到D中的赋值中吗?

时间:2013-11-16 12:58:43

标签: reference d ownership copy-assignment

当我在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?)
    }
}

2 个答案:

答案 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讨论了类,包括如何分配和复制它们。