Created
September 21, 2018 07:41
-
-
Save mmmunk/5858634ee0d2c42d7a6af97f83b8c8fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type | |
TRefCountObject = class(TObject) | |
protected | |
ExtraReferencesCount: Integer; { Default 0 } | |
public | |
procedure Free; | |
function GetReference: TRefCountObject; | |
end; | |
procedure TRefCountObject.Free; | |
begin | |
if Self <> nil then | |
if ExtraReferencesCount > 0 then | |
Dec(ExtraReferencesCount) | |
else | |
inherited Free; | |
end; | |
function TRefCountObject.GetReference: TRefCountObject; | |
begin | |
Inc(ExtraReferencesCount); | |
Result:=Self; | |
end; | |
// ---------- Test ---------- | |
procedure TestCreate; | |
begin | |
if obj = nil then | |
obj:=TRefCountObject.Create | |
else | |
obj:=obj.GetReference; | |
end; | |
procedure testGet; | |
begin | |
if obj <> nil then | |
Caption:=IntToStr(obj.ExtraReferencesCount) | |
else | |
Caption:='nil'; | |
end; | |
procedure TestDestroy; | |
begin | |
if obj <> nil then | |
if obj.ExtraReferencesCount > 0 then | |
Obj.Free | |
else | |
FreeAndNil(obj); | |
end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment