[fpc-pascal] Generic a "Clone" method

Torsten Bonde Christiansen tc at epidata.dk
Tue Jun 16 14:27:07 CEST 2009


Martin Friebe wrote:
>
> There is Object.InstanceSize, which sounds as if it may be what you 
> are looking for.
> But you have a bigger problem than that.
Thanks - i'll try 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.
Can this be avoided by using the "UniqueString(..)"  method?
>
> 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 at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal




More information about the fpc-pascal mailing list