为什么FreeAndNil实现在Free之前做Nil? [英] Why FreeAndNil implementation doing Nil before Free?

查看:242
本文介绍了为什么FreeAndNil实现在Free之前做Nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您查看FreeAndNil过程的代码,则会看到:

If you will look at the code of FreeAndNil procedure you will see:

procedure FreeAndNil(var Obj);
var
  Temp: TObject;
begin
  Temp := TObject(Obj);
  Pointer(Obj) := nil;
  Temp.Free;
end;

仅在销毁对象引用之后才将Nil分配给对象引用的原因是什么?反之亦然?

What is the reason they assigning Nil to an object reference and only after this destroying it? Why not vice-versa?

推荐答案

我可以考虑这样做的两个原因,但这两个原因似乎都不是很吸引人.

I can think of two reasons for doing it this way round, neither of which seems at all compelling.

原因1:确保在引发异常的情况下将引用设置为nil

该实现实现了这一点.如果析构函数引发,则引用仍设置为nil.另一种方法是使用finally块:

The implementation achieves this. If the destructor raises, then the reference is still set to nil. Another way to do so would be with a finally block:

try
  TObject(Obj).Free;
finally
  TObject(Obj) := nil;
end;

此方面的缺点是性能.特别是在x86上,try/finally有点贵.在这样的基本例程中,应谨慎避免这种花费.

The downside of this is performance. Particularly on x86 a try/finally is a little expensive. In such a fundamental routine it is prudent to avoid this expense.

为什么我会不惜一切代价求零的欲望?好吧,一旦析构函数开始失败,您就应该放弃.您不再能清楚地说明程序的状态.您无法确定失败的原因以及程序处于何种状态.我认为面对析构函数提出的正确做法是终止进程.

Why do I find the desire to nil at all costs not to be compelling? Well, as soon as destructor start failing you may as well give up. You can no longer reason clearly about your program's state. You cannot tell what failed and what state your program is in. It is my view that the correct course of action in the face of a destructor that raises is to terminate the process.

原因2:确保其他线程可以检测到该对象被破坏

同样可以实现,但是没有实际用途.是的,您可以测试是否分配了参考.但是那又怎样呢?如果没有同步,则另一个线程无法调用对象上的方法.您所要做的就是了解对象是否还活着.如果是这样,为什么在析构函数运行之前或之后更改此状态会很重要?

Again this is achieved but it is of no practical use. Yes you can test whether the reference is assigned or not. But then what? The other thread cannot call methods on the object without synchronization. All you could do is learn whether or not the object is alive. And if that is so, why would it matter if this status changed before or after the destructor runs?

因此,尽管我提出这可能是一个原因,但我不敢相信Embarcadero中的任何人都会被这一论点所左右.

So whilst I present this as a possible reason I cannot believe that anyone in Embarcadero was really swayed by this argument.

这篇关于为什么FreeAndNil实现在Free之前做Nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆