I was wondering, is there anything in the RTTI of Delphi that will do the same as MemberwiseClone does in C# for the simple implementation of the prototype pattern. I saw so
Object.MemberwiseClone Method makes a shallow copy of the object following some very simple rules and taking advantage of how the .NET garbage collector works.
object
.The part about the value types can easily be duplicated with Delphi. Duplicating the reference-type behavior with Delphi, while technically easy, will not provide the expected result: Delphi code is expected to .free
the objects it creates, and it uses a owner-owned
paradigm to make sure that happens. The usual pattern is to free objects created by the owner-object from the destructor. If you make a shalow-copy of the object, this results in failure. Here's an example:
A.Free;
B.Free;
- this automatically calls B.Free
, but unfortunately B was already freed when we freed A!We could attempt a deep-copy
, as David suggests, but that poses some equally difficult problems:
Application
?Putting this all together we can only reach one conclusion: We can't have a general purpose, Delphi equivalent of MemberwiseClone
. We can have a partial look-alike for simpler objects with uncomplicated interactions, but that's not nearly as appealing!