Torsten Bonde Christiansen wrote:
Hi.

I was wondering if it is posible to make this type of construct for creating a generic Clone method:

(I put it in pastebin):  http://pastebin.com/fb495ed7

Explained in words - I'm trying to make a clone method that should be able to copy the content of private variables to a destination object. Naturally this destination would have to be of the same class as the original, but is it posible to determine the size of used space in each derived class, simply by using Sizeof(...). Or do I need to create a seperate clone method for each individual derived class.

If it is posible, what memory copy function should I use?

There is Object.InstanceSize, which sounds as if it may be what you are looking for.
But you have a bigger problem than that.

If any member (object variable) is of a ref-counted type (that is strings and dynamic arrays), then any "memory copy" will mess up.

Because in the objects memory, there only are the pointers to the data of strings, and dyn-arrays. If you copy those pointer by hand, then the reference-counts in the actual string or dyn-array are not updated.
this leads to at least 2 problems.

1)
If the original object was the only holder (or last remaining) of a reference to this string, and your original or new object is destroyed, the ref-count goes down to zero => the string is freed, and the other object points to unallocated memory, or meory allocated to some new/other data) => crash

2)
Again if, your old object was the only holder, then the ref-count is still 1. Strings are "copy on modify", => 2 copies of a string share memory until one is changed (in which case a copy is made). The need for making the copy is determined by ref-count > 1. Your ref-count is 1 => no copy is made, the new object is updating the strings of the old object too

Best Regards
Martin



_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal

Reply via email to