Caleb C. wrote:0
In general, +clone+ and +dup+ may have different
semantics in descendent classes. While +clone+ is used to duplicate
an object, including its internal state, +dup+ typically uses the
class of the descendent object to create the new instance.
Frankly, I’ve never been real sure what this is supposed to mean
I think what it means is: clone just copies all the instance
variables, whilst dup calls self.class.new().
It’s quite common for initialize() to have all sorts of side effects,
creating new objects and so on. So you can expect dup to do all this,
whilst you can expect clone to create an identical object with all the
instance variables pointing at the same objects.
Nothing enforces that of course, so it’s just a convention.
The only real differences I can see are:
- clone also copies the frozen state of the object
- clone makes a copy of the singleton class
(whereas in dup, by default the newly-created object has an empty
singleton class; it’s assumed that if there are any methods to be added
to that, your own dup method will do that for you, possibly with the
assistance of your initialize method)
initialize_copy apparently is used by both dup and clone. You’re
right, that should be defined (overridden?) instead of dup/clone
themselves. I rarely remember that.
I’m not sure I agree with that. The default implementation of both dup
and clone does this, as it’s the only reasonable thing for Object to do
without any knowledge of its subclasses. But I think the spirit of dup
described above is that dup defined in a subclass should initialize it
using its constructor.
Since I never use clone, it’s a moot point for me as to what it should
do in a subclass.
Regards,
Brian.