TReferenceCountedObject

Object that keeps track of the number of times it is referenced from other objects

Inheritance

LevelAncestorDescription
1TObjectUltimate ancestor in a class hierarchy
2TBaseObjectA base class for objects that can be used instead of TObject.
3TReferenceCountedObject

Source

Object_.ReferenceCounted.pas (26)

Description

Whenever the ReferenceCount drops to zero the object is freed. The reference count of an object is incremented by calling AddReference and decremented by calling ReleaseReference. Use a TReferenceCountedObject when there is no clear owner for the object and instead it should be shared by a group of objects. Please remind that this memory management technique is not capable of reclaiming objects that reference each other, either directly or indirectly. To be able to reclaim such object cycles you have to explicitly break a cycle by removing one of the problematic references.

When using reference counted objects the following rules should be followed:

  • An object is created with reference count 0
  • A function that returns a reference counted object does not add a reference which is consistent with the previous rule
  • When assigning a reference counted object to a local variable of a function:
    • The call to AddReference immediately follows the assignment:
      1 2 Value := CreateReferenceCountedObject(); Value.AddReference();
    • The corresponding call to ReleaseReference should be in the same function
  • When using a reference counted object as a member of an object that member should be a property:
    • The property reads a field
    • The property writes using a function:
      1 2 3 4 5 6 7 if Value <> ReferenceCountedObject then begin Value.AddReference(); ReferenceCountedObject.ReleaseReference(); FReferenceCountedObject := Value; end;
    • Destroy always calls ReleaseReference.
  • When the result of a function already has a reference count higher than zero and that object is released within the function, like when removing the object from a collection, use DiscardReference to allow the reference count to drop to zero without freeing the object:
    1 2 3 4 5 Result := Elements[Index]; Result.AddReference(); Elements.RemoveAt(Index); Result.DiscardReference();

Fields

ScopeVisibilityTypeNameDescription
InstanceprotectedTInteger32FReferenceCount

Methods

ScopeVisibilityResultNameDescription
InstanceprotectedTInteger32IncreaseReferenceCount()
InstanceprotectedTInteger32DecreaseReferenceCount()
InstancepublicCreate()
InstancepublicDestroy()
InstancepublicFree(DummyParameterToHideInheritedMethod: TInteger32)
InstancepublicAddReference()Increments ReferenceCount
InstancepublicReleaseReference()Decrements ReferenceCount and calls Free when the new reference count is zero
InstancepublicDiscard()Calls AddReference directly followed by ReleaseReference
InstancepublicDiscardReference()Decrements ReferenceCount and does not call Free when the new reference count is zero