Your optimization, complex as it may seem, is actually trivial, in the sense that it likely emits the same code than the previous one.
Think in low level operations, not syntax: one condition, one branch. It is difficult to do less.
UPDATE: I've noticed that I didn't really answer your question: Can it be done faster? Well, yes! You can write a subclass just for the uninitialized value.
class InvalidObject : public Object
{
public:
const Object* clone() const {
return this;
}
};
And make the global INVALID_OBJECT
an instance of this class:
Object *INVALID_OBJECT = new InvalidObject();
Now you don't need the condition in any of the clone()
overrides:
class DerivedObject : public Object
{
public:
const Object* clone() const {
return new DerivedObject(*this);
}
};
Naturally, depending on the structure of your hierarchy and the definition of your INVALID_OBJECT
instance, you may need to write a Invalid*
subclass for each DerivedObject
type.