[fpc-pascal] Generic a "Clone" method

Martin Friebe fpc at mfriebe.de
Tue Jun 16 18:42:37 CEST 2009

Torsten Bonde Christiansen wrote:
> Martin Friebe wrote:
>> 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?
If you know where the strings are...; but then it's no longer unique.

You can try something else, but i have no idea where it leads too, or if 
its usable (in objpas mode)

 TFoo = object

Acts like a record, with methods, kind of.....

  var a, b: TFoo


Takes care of everything.

BUT those "objects" are like records. they do not allocate ne meory, 
each time you create them, they alloc mem when you *declare* them

if you pass them to a function in the arg list, they get copied. ( with 
"class" the pointer gets copied, because class is in reality a pointer.

  So you could declare
 TRealFoo = ^TFoo;

then write your constructor to return the pointer,
 every access would need the dereference of course => massive change to 

and so on.
If it is for you, you have to RT(F)M yourself....


More information about the fpc-pascal mailing list