Can someone give an example of a situation where a shallow copy is needed?
Note that in some situations, shallow copy and deep copy are the same. This can happen when the object has no ownership over any of its subvariables; that is, all subvariables are aggregated. I'd like to see examples where the an object is composed from variables which it owns, and it still is desirable to copy them shallowly.
Remark: I don't care in which language the examples are given. I'm asking this question from a C++/Java/C# point of view, although I think copying is a language agnostic concept.
Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster. Deep copy is comparatively slower.
Shallow copies are useful when you want to make copies of classes that share one large underlying data structure or set of data.
In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored.
Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields. Shallow copy is fast and also less expensive. Deep copy is slow and very expensive.
When the owned variables are immutable types, a shallow copy is sufficient. A deep copy is possible, but would only result in additional memory use.
One possible use case is when the composed objects can be derived from state information that is present in the shallow copy and you want, for instance, to serialize your object.
You can store the shallow copy and then rebuild the complete object from the state upon deserialization.
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