对已经释放的对象的引用错误

对已经释放的对象的引用错误

本文介绍了对已经释放的对象的引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确保我们持有一个可用的对象的引用,即确定它还没有被释放,这个非零参考悬空。

解决方案

如果您使用FastMM4作为内存管理器,您可以检查该类是否不是 TFreeObject

或者,在更标准情况下,使用一个例程来验证你的对象是否是通过检查类VMT 来表示的。



已经有这样的ValidateObj功能在一段时间内(Ray Lischner和Hallvard Vassbotn):)



这是另一个:

 函数ValidateObj(Obj:TObject):指针; 
//在System.pas中查看{虚拟方法表条目}
begin
结果:= Obj;
如果分配(结果)然后
尝试
如果指针(PPointer(Obj)^)指针(指针(Cardinal(PPointer(Obj)^)+ Cardinal(vmtSelfPtr))^)然后
//对象无效
结果:= nil;

结果:= nil;
结束
结束

更新:有点谨慎...上述功能将确保结果为零或一个有效的非零对象。如果内存管理器已经重新分配了以前释放的内存,那么它不能保证Obj仍然是您的想法。


Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.

解决方案

If you're using FastMM4 as your Memory Manager, you can check that the class is not TFreeObject.
Or, in a more standard case, use a routine that will verify that your object is what it says it is by checking the class VMT.

There have been such ValidateObj functions hannging around for some time (by Ray Lischner and Hallvard Vassbotn: http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html)

Here's another:

function ValidateObj(Obj: TObject): Pointer;
// see { Virtual method table entries } in System.pas
begin
  Result := Obj;
  if Assigned(Result) then
    try
      if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then
        // object not valid anymore
        Result := nil;
    except
      Result := nil;
    end;
end;

Update: A bit of caution... The above function will ensure that the result is either nil or a valid non nil Object. It does not guarantee that the Obj is still what you think it is, in case where the Memory Manager has already reallocated that previously freed memory.

这篇关于对已经释放的对象的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:53