unit drefcounted;

interface

type
PRefCounted = ^TRefCounted;
TRefCounted = object
private
  FRefCount: LongInt;
  FAutoFree: Boolean;
protected
public
  constructor Init(AutoFree: Boolean);
  destructor DoDone; virtual;
  procedure IncRef;
  procedure Done;
  property RefCount: LongInt read FRefCount;
end;

implementation

constructor TRefCounted.Init(AutoFree: Boolean);
begin
  FAutoFree := AutoFree;
  FRefCount := 0;
end;

destructor TRefCounted.DoDone;
begin
end;

procedure TRefCounted.IncRef;
begin
  Inc(FRefCount);
end;

procedure TRefCounted.Done;
begin
  Dec(FRefCount);
  if FRefCount <= 0 then begin
    DoDone;
    if FAutoFree then
      FreeMem(@Self);
  end;
end;

end.
