clone() only partially doable; how to react?

Posted by hllnll on Programmers See other posts from Programmers or by hllnll
Published on 2014-08-21T17:30:07Z Indexed on 2014/08/21 22:26 UTC
Read the original article Hit count: 199

Filed under:

Suppose we have a class-hierarchy whose base class B requires a clone() method to be defined in its derivations. Whilst this works perfectly for most of them there is this one derivation X that holds an optional reference to a resource/object that can only be referenced from one instance of X. Whilst the rest of X can be cloned without problems this reference would have to be set to null/nil/nullptr.

What is the correct way to handle this situation?

  • X::clone() could throw an UncloneableException. Though this would be correct, it is not satisfying.
  • Set the reference to null/nil/nullptr and leave no notice of it. The user of X has to know about Xs "particularities".
  • Require derivations of B to define B::nearestClone(): the user of B has to be aware that the return value might not be a 1:1 clone.
  • Something else?

© Programmers or respective owner

Related posts about idioms