SpaceCowboy proposes the idiomatic clone
method, but overlooked 3 crucial details:
class Super
{
public:
virtual Super* clone() const { return new Super(*this); }
};
class Child: public Super
{
public:
virtual Child* clone() const { return new Child(*this); }
};
clone
is a const
method
clone
returns a pointer to the current class, not the base class
clone
returns a copy of the current object
The 2nd is very important, because it allows use to benefit from the fact that sometimes you have more type information than just a Super*
.
Also, I usually prefer clone
to provide a copy, and not merely a new object of the same type. Otherwise you're using an Exemplar
pattern to build new objects, but you're not cloning proper and the name is misleading.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…