我正在處理一個包含多個包的項目。在我的基本包一個,我宣佈一個智能指針,這樣的(這裏是完整的代碼):德爾福 - 智能指針構造函數的奇怪行爲
unit UTWSmartPointer;
interface
type
IWSmartPointer<T> = reference to function: T;
TWSmartPointer<T: class, constructor> = class(TInterfacedObject, IWSmartPointer<T>)
private
m_pInstance: T;
public
constructor Create; overload; virtual;
constructor Create(pInstance: T); overload; virtual;
destructor Destroy; override;
function Invoke: T; virtual;
end;
implementation
//---------------------------------------------------------------------------
constructor TWSmartPointer<T>.Create;
begin
inherited Create;
m_pInstance := T.Create;
end;
//---------------------------------------------------------------------------
constructor TWSmartPointer<T>.Create(pInstance: T);
begin
inherited Create;
m_pInstance := pInstance;
end;
//---------------------------------------------------------------------------
destructor TWSmartPointer<T>.Destroy;
begin
m_pInstance.Free;
m_pInstance := nil;
inherited Destroy;
end;
//---------------------------------------------------------------------------
function TWSmartPointer<T>.Invoke: T;
begin
Result := m_pInstance;
end;
//---------------------------------------------------------------------------
end.
在我的項目後來(在另包),我用這個智能指針與GDI +對象(一個TGpGraphicsPath)。我聲明瞭這樣的圖形路徑:
...
pGraphicsPath: IWSmartPointer<TGpGraphicsPath>;
...
pGraphicsPath := TWSmartPointer<TGpGraphicsPath>.Create();
...
但是,當我執行代碼時,屏幕上沒有畫任何東西。我沒有得到任何錯誤,沒有例外或訪問違規,只是一個空白頁面。但是,如果我只是改變我的代碼這樣的:
...
pGraphicsPath: IWSmartPointer<TGpGraphicsPath>;
...
pGraphicsPath := TWSmartPointer<TGpGraphicsPath>.Create(TGpGraphicsPath.Create);
...
然後都成爲精品,和我的道路究竟是畫如預期。但我不明白爲什麼第一個構造函數不能按預期工作。有人可以向我解釋這種奇怪的行爲?
Regards
我的猜測是,TGpGraphicsPath有一個可選的參數,在這種情況下TObject.Create將被調用,而不是TGpGraphicsPath.Create(optionalArgument) - 你必須注意的泛型。 – Dsm
@Remy事實證明,匿名方法實際上是接口,並且實現細節以這種方式被廣泛使用:http://stackoverflow.com/a/39955320 –
@Dsm TGpGraphicsPath'在其構造函數中沒有參數。 –