4

When I assign an object in D, will it be copied?

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?)
    }
}
Jeroen
  • 15,257
  • 12
  • 59
  • 102

2 Answers2

5

Only the reference is copied, the object itself isn't duplicated. You can explicitly duplicate the object by using .dup though.

kviiri
  • 3,282
  • 1
  • 21
  • 30
  • 2
    You would have to declare a `dup` method for whatever class you were trying to `dup` first, just like you would have to define a `clone` method in Java or C#. There is no built-in way to dup/clone/copy a class in D. – Jonathan M Davis Nov 16 '13 at 23:41
3

Classes are reference types, so when you have

Object o;

o is a reference to an Object rather than an actual Object, so copying it just copies the reference. It's just like with pointers.

auto a = new int;
*a = 5;

auto b = a;
assert(a is b);
assert(*a == *b);

*b = 5;
assert(*a == 5);

I would advise reading either The D Programming Language by Andrei Alexandrescu, or Ali Çehreli's D Programming Language Tutorial. In particular, this chapter of Ali's book discusses classes, including how to assign and copy them.

Jonathan M Davis
  • 37,181
  • 17
  • 72
  • 102