Will objects be copied in assignment in D?
-
21-12-2019 - |
Question
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?)
}
}
Solution
Only the reference is copied, the object itself isn't duplicated. You can explicitly duplicate the object by using .dup
though.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow