Assuring proper maintenance of Clone() in C++
In C++, I find it very useful to add a "Clone()" method to classes that are part of hierarchies requiring (especially polymorphic) duplication with a signature like this:
class Foo {
public:
virtual Foo* Clone() const;
};
This may look pretty, but it is very prone to bugs introduced by class maintenance. Whenever anyone adds a data member to this class, they've got to remember to update the Clone() method. Failing to 开发者_开发技巧results in often subtle errors. Unit tests won't find the error unless they are updated or the class has an equality comparison method and that is both unit tested and was updated to compare the new member. Maintainers won't get a compiler error. The Clone() method looks generic and is easy to overlook.
Does anyone else have a problem with Clone() for this reason? I tend to put a comment in the class's header file reminding maintainers to update Clone if they add data members. Is there a better idea out there? Would it be silly/pedantic to insert a #if/etc. directives to look for a change to the class size and report a warning/error?
Why not just use the copy constructor?
virtual Foo* Clone() const { return new Foo(*this); }
Edit: Oh wait, is Foo the BASE class, rather than the DERIVED class? Same principle.
virtual Foo* Clone() const { return new MyFavouriteDerived(*this); }
Just ensure that all derived classes implement clone in this way, and you won't have a problem. Private copy constructor is no problem, because the method is a member and thus can access it.
Ok, this question has me confused. Initially I thought you wanted to automatically create clone() and I was going to direct you to a discussion I was in a couple years back.
However...that doesn't seem like what you want. So I'll just address your assumptions:
Whenever anyone adds a data member to this class, they've got to remember to update the Clone() method.
Why?? Surely you've implemented clone() in terms of the copy constructor.
struct X { X* clone() const { return new X(*this); } };
Unit tests won't find the error unless they are updated or the class has an equality comparison method and that is both unit tested and was updated to compare the new member.
This shouldn't be a problem since you've surely updated the unit test BEFORE adding the member...
Does anyone else have a problem with Clone() for this reason?
No, I can say with certainty that I've never had your particular problems with clone().
精彩评论