当我在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?)
    }
}
有帮助吗?

解决方案

只有引用被复制,对象本身不被复制。您可以使用以下方法显式复制对象 .dup 不过。

其他提示

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

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);

我会建议阅读要么 D编程语言 由Andrei Alexandrescu,或Ali Çehreli的 D编程语言教程.特别是, 本章 阿里的书讨论了类,包括如何分配和复制它们。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top