【问题标题】:Reference counting in Delphi Interfaces [duplicate]Delphi接口中的引用计数[重复]
【发布时间】:2017-06-22 10:11:55
【问题描述】:

基本问题。 在 Button1Click 中,我创建了一个接口对象。创建后的引用计数为 0。 我将对象作为参数传递。引用计数在函数结束时增加,减少,当它为 0 时,它被销毁。我错过了什么吗?当我首先创建对象时,我在想引用计数应该是 1? lListFilter 没有持有对对象的引用?

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;

【问题讨论】:

    标签: delphi reference-counting


    【解决方案1】:

    Button1Click 中,lListFilter 被声明为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.
    

    【讨论】:

    • 谢谢戴夫!现在很清楚为什么 .create 没有增加引用计数,但我仍然困惑为什么 FillList(lListFilter) 确实增加了引用计数,因为它被错误地声明为 TPersistentListFilter..
    • 因为FillList 接受IPersistentListFilter 作为其参数
    • 因为'FillList'的'AFilter'参数被声明为'IPersistentListFilter'; 'lListFilter' 将传递 作为 'IPersistentListFilter',而不是'TPersistentListFilter'
    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2012-02-23
    • 2014-04-07
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多