4

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

2 回答 2

5

仅复制引用,不复制对象本身。您可以通过 using 显式复制对象.dup

于 2013-11-16T13:06:27.287 回答
3

类是引用类型,所以当你有

Object o;

o是对 an 的引用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。特别是,阿里书中的这一章讨论了类,包括如何分配和复制它们。

于 2013-11-16T23:49:53.367 回答