[fpc-pascal] Quick Modern Object Pascal Introduction, for Programmers
Michalis Kamburelis
michalis.kambi at gmail.com
Tue Jun 21 13:08:43 CEST 2016
2016-06-21 12:14 GMT+02:00 Marco van de Voort <marcov at 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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test_clone.lpr
Type: application/octet-stream
Size: 1063 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160621/cfaed792/attachment.obj>
More information about the fpc-pascal
mailing list