gpt4 book ai didi

delphi - Delphi接口(interface)引用计数的实现是面向 future 的

转载 作者:行者123 更新时间:2023-12-03 14:46:28 24 4
gpt4 key购买 nike

我有一个帮助器类,它将在整个应用程序中广泛使用。实现依赖于接口(interface)引用计数,大致思路是:

...
var
lHelper: IMyHelper;
begin
lHelper := TMyHelper.Create(some params);
...some code that doesn't have to access lHelper
end;

因此,实现依赖于 IMyHelper 在方法结束时超出范围,而不是之前。

所以我要问的是,我能否确定在未来的某个时候,如果在方法的其余部分中没有访问该变量,Delphi 编译器不会聪明地在创建接口(interface)后立即释放接口(interface)?

最佳答案

恕我直言,你可以对此充满信心。超出范围的模式可能对此方法的指令 block 保持全局性。这将是一个重大改变。

参见this comment from Barry Kelly (来自内河码头):

As to your earlier comment, about explicit variables: in the hypothetical (and breaking change) case, where we optimized interface variable usage, we would likely not only break the described RAII-like functionality but also the explicit variable approach too; the values assigned to FooNotifier and BarNotifier are not used, so "in theory" they can be freed up sooner, and potentially even reuse the same storage.

But of course, destruction of the interface can have side-effects, and that's what's being relied upon for the effect in the post. Changing the language such that side-effects like these have visible changes is not something we do willingly.

因此您可以猜测 Embarcadero 不会在这里引入任何向后兼容性更改。重新使用接口(interface)内存的好处不值得破坏兼容性并引入副作用:保存指针(4 或 8 字节)现在不值得,特别是当堆栈已经分配并对齐时(x64 模型使用比 x86 更多的堆栈)。

只有当垃圾收集器被引入该语言时(从我个人的角度来看,我不希望这样做),对象的生命周期可能会改变。但在这种情况下,使用生命周期可能会更长。

在所有情况下,您都可以创建自己的代码,以确保它将在方法结束时释放:

var
lHelper: IMyHelper;
begin
lHelper := TMyHelper.Create(some params);
try
...some code that doesn't have to access lHelper
finally
lHelper := nil; // release the interface count by yourself
end;
end;

事实上,这是编译器已经生成的代码。编写此代码将是完全多余的,但它将确保编译器不会欺骗您。

在谈到接口(interface)和引用计数时,请考虑 Delphi 中潜在的循环引用问题。请参阅this great article (i.e. "Example 2-15")关于接口(interface)循环引用的“弱指针”的需要。

其他语言(如 Java 或 C#)使用垃圾收集器来解决此问题。 Objective C 使用显式的“弱指针归零”机制来解决它 - 请参阅 this discussionthis SO answer for a potential implementation 。也许 future 版本的 Delphi 可能会考虑使用类似于 Objective C 中引入的 ARC 模型的实现。但我怀疑会有一个显式的语法来保持与现有代码的兼容性。

关于delphi - Delphi接口(interface)引用计数的实现是面向 future 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9093457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com