(转)智能指针的另外一种实现 - Smart pointers in Delphi

Strongly-typed smart pointers are now possible in Delphi, leveraging the work on generics. Here's a simple smart pointer type:

  TSmartPointer<T: class> = record
  strict 
private
    FValue: T;
    FLifetime: IInterface;
  
public
    
constructor Create(const AValue: T); overload;
    
class operator Implicit(const AValue: T): TSmartPointer<T>;
    
property Value: T read FValue;
  
end;

Here it is in action, where TLifetimeWatcher is a little class that executes some code when it dies:

procedure UseIt;
var
  x: TSmartPointer
<TLifetimeWatcher>;
begin
  x :
= TLifetimeWatcher.Create(procedure
  
begin
    Writeln(
'I died.');
  
end);
end;

Here's the full project code that defines TSmartPointer<>, TLifetimeWatcher, and the above test routine:

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TLifetimeWatcher 
= class(TInterfacedObject)
  
private
    FWhenDone: TProc;
  
public
    
constructor Create(const AWhenDone: TProc);
    
destructor Destroy; override;
  
end;

{ TLifetimeWatcher }

constructor TLifetimeWatcher.Create(const AWhenDone: TProc);
begin
  FWhenDone :
= AWhenDone;
end;

destructor TLifetimeWatcher.Destroy;
begin
  
if Assigned(FWhenDone) then
    FWhenDone;
  
inherited;
end;

type
  TSmartPointer
<T: class> = record
  strict 
private
    FValue: T;
    FLifetime: IInterface;
  
public
    
constructor Create(const AValue: T); overload;
    
class operator Implicit(const AValue: T): TSmartPointer<T>;
    
property Value: T read FValue;
  
end;

{ TSmartPointer<T> }

constructor TSmartPointer<T>.Create(const AValue: T);
begin
  FValue :
= AValue;
  FLifetime :
= TLifetimeWatcher.Create(procedure
  
begin
    AValue.Free;
  
end);
end;

class operator TSmartPointer<T>.Implicit(const AValue: T): TSmartPointer<T>;
begin
  Result :
= TSmartPointer<T>.Create(AValue);
end;

procedure UseIt;
var
  x: TSmartPointer
<TLifetimeWatcher>;
begin
  x :
= TLifetimeWatcher.Create(procedure
  
begin
    Writeln(
'I died.');
  
end);
end;

begin
  
try
    UseIt;
    Readln;
  
except
    on E:Exception 
do
      Writeln(E.Classname, 
'', E.Message);
  
end;
end.

 

Update: Fixed capture - was capturing a location in the structure, which of course will be freely copied etc.

 

原帖地址: http://barrkel.blogspot.com/2008/09/smart-pointers-in-delphi.html

转载于:https://www.cnblogs.com/felixYeou/archive/2008/09/07/1286353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值