Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a default polymorphic cloning operator mechanism in c++?

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?

like image 822
galinette Avatar asked Oct 30 '25 00:10

galinette


1 Answers

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 :))

like image 153
sehe Avatar answered Oct 31 '25 15:10

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!