2017-06-22 77 views
0

基本問題。 在Button1Click中,我創建了一個接口對象。創建後引用計數爲0. 我將該對象作爲參數傳遞。 Ref計數增加,在函數結束時減少,因爲它0,它被破壞。我想念什麼?當我首先創建對象時,我認爲參考計數應該是1? lListFilter沒有持有對象的引用?Delphi接口中的引用計數

type 
    IPersistentListFilter = Interface(IInterface) 
     ['{57cdcf89-60ee-4b3c-99fd-177b4b98d7e5}'] 
     procedure IncludeObject; 
end; 

procedure FillList(AFilter : IPersistentListFilter); 

type 
TPersistentListFilter = class(TInterfacedObject, IPersistentListFilter) 
    procedure IncludeObject; 
    constructor Create; 
    destructor Destroy; override; 
end; 

implementation 

procedure FillList(AFilter: IPersistentListFilter); 
begin 
    AFilter.IncludeObject; 
end; 

constructor TPersistentListFilter.Create; 
begin 
    inherited; 
end; 

destructor TPersistentListFilter.Destroy; 
begin 
    inherited; 
end; 

procedure TPersistentListFilter.IncludeObject; 
begin 
    // do nothing 
end; 

procedure TForm8.Button1Click(Sender: TObject); 
var 
    lListFilter: TPersistentListFilter; 
begin 
    lListFilter := TPersistentListFilter.Create; 
    // ref count is 0 
    FillList(lListFilter); 
    // lListFilter has been destroyed 
    FillList(lListFilter); // --> error 
end; 

回答

2

Button1ClicklListFilter被聲明爲TPersistentListFilter,不IPersistentListFilter一個實例。因此,在創建lListFilter時不會發生引用計數。

lListFilter需要被聲明爲IPersistentListFilter

procedure TForm8.Button1Click(Sender: TObject); 
var 
    lListFilter: IPersistentListFilter; 
begin 
    lListFilter := TPersistentListFilter.Create; 
    // ref count will be 1 

    // ref count will go to 2 during call to FillList 
    FillList(lListFilter); 

    // ref count will be back to 1 

    // ref count will go to 2 during call to FillList 
    FillList(lListFilter); 

    // ref count will be back to 1 

end; // ref count will go to 0 as lListFilter goes out of scope 
     // and is destroyed. 
+0

Thnks戴夫!現在清楚爲什麼.create沒有增加引用計數,但即時通訊仍然困惑爲什麼FillList(lListFilter)確實增加了引用計數,因爲它已被錯誤地聲明爲TPersistentListFilter。 – siwmas

+1

因爲FillList接受IPersistentListFilter作爲它的參數 –

+0

因爲'FillList'的'AFilter'參數被聲明爲'IPersistentListFilter'; 'lListFilter'將作爲*'IPersistentListFilter'傳遞*,而不是'TPersistentListFilter' –