On Fri, May 19, 2017 at 05:48:55PM +0000, Stanislav Blinov via Digitalmars-d wrote: > On Friday, 19 May 2017 at 17:05:09 UTC, H. S. Teoh wrote: [...] > > AFAIK, there is no way to clone classes, unless the class writer > > implemented it explicitly. Only arrays support .dup, no other type does > > (unless user code explicitly implements it, or its equivalent). > > > > > > T > > Well, not that it's a complete implementation or anything, but it > definitely could be done with a library: > > /// Make a shallow clone of a class instance > /// (members that are classes are not cloned) [...]
That's the problem right there: you cannot guarantee that a shallow copy will have the correct semantics. For example, modifying a class member through the original copy will also modify what is seen through the clone, which may not be the intention. Also, you have to take care that if the class member is ref-counted, the clone function needs to increment the refcount, otherwise you could end up with a dangling pointer. Meaning, in the general case, you need to be careful about calling postblits and such. Furthermore, a generic deep-copying clone function may not be possible in the general case, because sometimes you don't know if a reference member is intended to be a reference to external data, or an owned value that needs to be deep-copied. For example, if a class C encapsulates a container of references to data, then C.clone should not copy the data, but if a class D is a container of references to data that it owns, then the data should be copied. A generic function cannot decide which one it is unless the intent is made clear, e.g. via a standard UDA, or some other such means. T -- It's amazing how careful choice of punctuation can leave you hanging:
