3

I mean, a cloning operator, which by default use the copy constructor and new operator to return a new object. So that if the declaration in the base class is virtual, it would automatically provide a polymorphic cloning mechanism (any class should not be virtual by default)

Advantages:

  • Avoid doing Derived * clone() const { return new Derived(*this); } everywhere

  • Allow standard smart pointers such as std::unique_ptr or a dedicated copyable one to clone the object without having them rely on a non standard semantic

Whay would be the risk/drawback?

galinette
  • 8,896
  • 2
  • 36
  • 87

1 Answers1

7

Because, pay for what you need (if it were automatic for any type, then all classes would be virtual).

There's nothing preventing you from implementing this as a CRTP base class, so language support is unneeded.

You could file a proposal adding such a base class (along with a value_ptr<T, std::default_clone<T> > and suitable specializations :))

sehe
  • 374,641
  • 47
  • 450
  • 633
  • No, the class would be virtual only if the cloning operator in the base class was declared virtual. As with a destructor. – galinette Jun 06 '14 at 07:42
  • 1
    What use would a non-virtual clone operation have? – sehe Jun 06 '14 at 07:42
  • Your proposal would imply multiple inheritance where it's not needed, if I'm right. – galinette Jun 06 '14 at 07:43
  • The use of non-virtual clone would be nothing more than provide the semantic for a standard copyable managed pointer, and avoiding making classes virtual by default... – galinette Jun 06 '14 at 07:45
  • Not if you just use the common base class approach, like many popular managed environment already do (CLR, LVM, ParrotVM etc. etc). – sehe Jun 06 '14 at 07:45
  • How do you implement cloning without defining a clone function in any derived class, and without multiple inheritance? This could be another question though – galinette Jun 06 '14 at 07:47
  • Well, I just read about CRTP polymorphic cloning with several levels of inheritance, constructors, etc... and this is awfully heavy... much more than defining clone everywhere. And still, there is no "standard" cloning semantic which would then be usable in a std::copyable_unique_ptr. Not convincing – galinette Jun 06 '14 at 08:21
  • @galinette I think, at this point, you need to define the semantics for your designated clone operation. Of course there's the age-old c++ idiom to have a free function `clone(T*)` and look up the appropriate implementation by ADL. This makes for decoupling, extensibility etc. instead of complicating the type system. – sehe Jun 06 '14 at 08:35