在C++中可以利用栈实现智能指针,可是在Delphi中由于所有的对象都是堆对象,无法利用栈对象。虽然在Delphi2007版本中已经有类似的栈结构,但是仍然不能实现完全意义上的指针。但是Delphi中可以利用另外一样东西实现智能指针--接口。附上源码:
- unit AutoPtr;
- interface
- uses
- SysUtils, SyncObjs;
- type
- { TAutoPtrObject - 智能指针对象 }
- TAutoPtrObject = class(TInterfacedObject)
- private
- FObject: TObject;
- public
- constructor Create(AObject: TObject); virtual;
- destructor Destroy; override;
- end;
- { TAutoLockObject - 智能线程锁 }
- TAutoLockObject = class(TInterfacedObject)
- private
- FSection: TCriticalSection;
- public
- constructor Create(ASection: TCriticalSection); virtual;
- destructor Destroy; override;
- end;
- function AutoFree(AObject: TObject): IInterface;
- function AutoLock(ASection: TCriticalSection): IInterface;
- implementation
- //------------------------------------------------------------------------------
- // 自动释放对象函数(对象必须由外部创建, 离开栈作用域释放)
- //------------------------------------------------------------------------------
- function AutoFree(AObject: TObject): IInterface;
- begin
- Result := TAutoPtrObject.Create(AObject);
- end;
- //------------------------------------------------------------------------------
- // 自动释放线程锁(对象必须由外部创建,离开栈作用域释放)
- //------------------------------------------------------------------------------
- function AutoLock(ASection: TCriticalSection): IInterface;
- begin
- Result := TAutoLockObject.Create(ASection);
- end;
- { TAutoPtrObject }
- constructor TAutoPtrObject.Create(AObject: TObject);
- begin
- FObject := AObject;
- end;
- destructor TAutoPtrObject.Destroy;
- begin
- // 智能指针在方法退出时销毁,同时销毁所管理的堆对象
- try FreeAndNil(FObject); except end;
- inherited;
- end;
- { TAutoLockObject }
- constructor TAutoLockObject.Create(ASection: TCriticalSection);
- begin
- inherited Create;
- Assert(ASection <> nil);
- FSection := ASection;
- FSection.Enter;
- end;
- destructor TAutoLockObject.Destroy;
- begin
- FSection.Leave;
- inherited;
- end;
- end.
不过利用接口实现的智能指针经过本人测试,会比较正常Try Finally 要多用一倍的时间。