[fpc-devel] Management operators AddRef and Copy vs Copy

Florian Klämpfl florian at freepascal.org
Sun Apr 10 14:45:45 CEST 2016


Am 10.04.2016 um 13:06 schrieb Maciej Izak:
> Hi,
> 
> Sven proposed that we need to discuss AddRef operator (important part of smart pointers implementation).
> 
> AddRef is used when record is passed as parameter to method/function by value (for records to large
> to copy (only the address is pushed)). AddRef is used also for dynamic array operations (temporary
> for SetLength operation and for Copy operation for already copied data by move).
> 
> AddRef is much faster than Copy (all data already exist, so we don't need to copy anything). AddRef
> is used to increment ref count for managed types.
> 
> IMO the best solution is to implement two operators:
> 
>     class operator AddRef(var aFoo: TFoo);
>     class operator Copy(constref aSrc: TFoo; var aDst: TFoo);
> 
> also is possible to implement single operator:
> 
>     class operator Copy(aSrc: PFoo; var aDst: TFoo);
> 
> aSrc in that case can be nil (for AddRef operation). Anyway that is inelegant solution...
> 
> Any other solution means big performance loss for RTL operations for dynamic arrays.
> 

I think this is the wrong way:
- AddRef means only to increase the ref. count of the passed data structure
- Copy is no deep copy, it means only: copy the current data structure, if it references managed
types, their ref. count is increased but they are not copied

Example with dyn. arrays:
- AddRef increases the ref. count of the passed array, not its members
- Copy creates a copy of the array, if the members of the array are managed, their ref. count is
increased

So I would call the operator Copy, in case of custom implemented ref. counted records, this would be
an AddRef operation. For a real copy, a procedure like Clone should be declared.



More information about the fpc-devel mailing list