Given an object that has a variable which it doesn't own; that is, the variable is composed by aggregation instead of composition. Will a deep copy operation copy the variable or only the link to it?
I like the distinction that you are making here between the role of composition and aggregation in the context of a deep copy.
I am going to go against the other answer and say: no, an object should not deep-copy another object that it doesn't own.
One would expect a deep copy of an object to be (at least initially) identical to the original. If a deep copy were made of a reference that the original didn't own, then this leaves open the question of what owns the new copy. If the clone owns it, then it would not be identical to the original object. It would be an object like the original, except it owns the reference to one of its aggregated members. This would surely lead to chaos. If the clone doesn't own it, then who does?
This problem of ownership is especially important in non-garbage-collected languages, but it also creates problems even with a garbage collector. For example, if the clone is made to allow uncommitted changes to an object, are changes to be allowed on this other object that it references? If changes are not allowed, then there was no reason to deep-copy it. If changes are allowed, then how are those changes to be committed, since the object being modified doesn't control this referenced object? Sure, a mechanism for this could be contrived, but it would surly mean that the cloned object is overstepping its responsibilities, and the program would be a maintenance nightmare.
A deep copy operation that includes unowned objects also leads to problems of infinite (or at least excessive) copy operations. Suppose an object is part of a collection, and further suppose the object requires a reference to the collection. A naive deep-copy operation on that object would then create a new copy of the collection and each of its members. Even assuming that we avoid the problem of infinite recursion, and keep all the references consistent among this new set of objects, it is still excessive for most purposes, and for those cases where a new collection is desired, wouldn't it make more sense to deep-copy the collection itself, rather than one of its members, for this purpose?
I think a deep-copy that only includes owned objects, as you suggest, is the only sane approach for most purposes.
Deep copy in oposite to shallow one should copy whole object recursively to the ground and make completely new copy of object and all contained objects.
So yes, it should copy variables, not only links..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With