2016-06-21 12:14 GMT+02:00 Marco van de Voort <mar...@stack.nl>: > In our previous episode, Michalis Kamburelis said: >> >> - A section about TPersistent.Assign. This is the "basic approach to >> cloning" that should probably be shown first. See it here: >> http://michalis.ii.uni.wroc.pl/~michalis/modern_pascal_introduction/modern_pascal_introduction.html#_cloning_tpersistent_assign > > See also > http://stackoverflow.com/questions/4041760/correct-way-to-duplicate-delphi-object/4041906#4041906 > > That is for an own root class and pre class helpers, but you could do it also > in or TPersistent > helper: > > type tpersisthelp = class helper for TPersistent > function Clone(t: TPersistentClass = nil): TPersistent; > end; > > function tpersisthelp.Clone(t: TPersistentClass = nil): TPersistent; > begin > if Assigned(t) then > Result := t.Create > else > Result := TPersistentClass(Self.ClassType).Create; > Result.Assign(Self); > end; > > Since TComponent declares a virtual destructor that might even be better.
I saw your post on stackoverflow before writing my article:) But doing this on TPersistent means that you avoid calling the constructor of the actual class. If you use this helper on a class TMyClass, you will have an instance of TMyClass that "bypassed" the constructor of TMyClass. Only "TPersistent.Create" was called. I suspect that in real-world usage, a lot of classes will fail to work correctly then, since code inside TMyClass often assumes that TMyClass constructor was performed. I know that a lot of my own classes will fail because of this... That's why I would limit this usage only to the cases when you have a virtual constructor on the base class. Only then the final class has a chance to execute it's proper constructor. Regards, Michalis
test_clone.lpr
Description: Binary data
_______________________________________________ fpc-pascal maillist - fpc-pascal@lists.freepascal.org http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal