스마트 포인터(Smart Pointer)의 구현

2650 단어 DELPHI
{******************************************************
*
* Delphi Smart Pointer class
* AutoPtr
* Version 0.2 beta
* Yang Qinqing @ http://www.cnblogs.com/felixyeou
*
*******************************************************}
unitAutoPtr;
interface
uses
  SysUtils,
  TypInfo;
type
  IAutoPtr=interface
    ['{86DB82D6-9A32-4A6A-9191-2E0DFE083C38}']
    functionGet:T;
    functionRelease:T;
    procedureReset(aObj:T);
  end;
  TAutoPtr=class(TInterfacedObject,IAutoPtr)
  private
     fObj:T;
    fTypeInfo:PTypeInfo;
    procedureFreeObj;
  public
     classfunctionNew(aObj:T):IAutoPtr;overload;
    classfunctionNew:IAutoPtr;overload;
     constructorCreate(aObj:T);virtual;
     destructorDestroy;override;
    functionGet:T;
    functionRelease:T;
    procedureReset(aObj:T);
  end;
implementation
{TAutoPtr}
constructorTAutoPtr.Create(aObj:T);
begin
  fObj:=aObj;
  //       
  fTypeInfo:=TypeInfo(T);
end;
classfunctionTAutoPtr.New(aObj:T):IAutoPtr;
begin
  Result:=TAutoPtr.Create(aObj)asIAutoPtr;
end;
functionTAutoPtr.Release:T;
begin
  Result:=fObj;
  //fObj:=nil
  Integer((@fObj)^):=0;
end;
procedureTAutoPtr.Reset(aObj:T);
begin
  //aObj<>fObjthen
  ifInteger((@aObj)^)<>Integer((@fObj)^)then
  begin
    FreeObj;
    fObj:=aObj;
  end;
end;
destructorTAutoPtr.Destroy;
begin
  //iffObj=nilthen..
  ifInteger((@fObj)^)<>0then
    FreeObj;
  fTypeInfo:=nil;
  inherited;
end;
procedureTAutoPtr.FreeObj;
begin
  //    TypeInfo  ,   T Pointer
  //             
  iffTypeInfo=nilthen
    //FreeMem(Pointer((@fObj)^))
    //      Dispose,  Dispose      FreeMem:
    //PUSH  EAX
    //CALL  _Finalize
    //POP  EAX
    //CALL  _FreeMem
    Dispose(Pointer((@fObj)^))
  else
  begin
    casefTypeInfo.Kindof
      tkClass:
        //  Object.Free,    DestructorDispose(virtual)  
        //            
        TObject((@fObj)^).Free;
      tkArray,tkDynArray:
        //           
    end;
  end;
  //fobj:=nil;
  Integer((@fObj)^):=0;
end;
functionTAutoPtr.Get:T;
begin
  Result:=fObj;
end;
classfunctionTAutoPtr.New:IAutoPtr;
var
  typInfo:PTypeInfo;
  obj:TObject;
  objNew:T;
begin
  typInfo:=TypeInfo(T);
  //       class    ,         
  //     Delphi         
  //1、GetMem(p,100);
  //2、New(p);
  if(typInfo<>nil)and(typInfo.Kind=tkClass)then
  begin
    //  T                
    obj:=GetTypeData(typInfo).ClassType.Create;
    //          
    objNew:=T((@obj)^);
    Exit(New(objNew));
  end;
  raiseException.Create('    class    。');
end;

좋은 웹페이지 즐겨찾기