There are (at least) two kinds of cloning. Most references talk about shallow and deep cloning, but in reality there are shades inbetween.
The key problem is the tension between "how much should be copied" and "how much should be shared".
Consider an Order
object, containing references to a Customer
, an Address
and to a List
of `OrderLines'.
If you wanted to Clone()
an Order
, what's involved?
"Just copying the memory block" would give you a new Order
, but one that shared the Customer
, Address
and the same List
of `OrderLines'. (Remember that object members are stored by reference, so when you duplicate the memory block, you end up with two references to the same object).
Clearly, you don't want to share the List
of OrderLines' between the two
Orders. In fact, you probably want to clone each
OrderLine` as well.
If you were working with a general purpose Clone()
method, how would that method know which members should be recursively cloned, and which should not?
Generally speaking, this is an intractable problem - which is why it's up to individual objects to implement appropriate semantics for their situation.
One final note: even when I do create the ability to Clone()
objects, I don't tend to create a Clone()
method, instead prefering a copy constructor - a constructor that accepts another object as a basis. If you can't find Clone()
, look for that.