如果销毁对象后使用它,为什么我没有收到异常? [英] Why I don't receive Exception if I use the object after I destroy it?

查看:61
本文介绍了如果销毁对象后使用它,为什么我没有收到异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以正常工作,但不行!当我单击Button1时,首先销毁了该对象,然后使用了它的Value,并且没有收到任何访问冲突之类的信息。甚至,乘运算给出了正确的结果,证明 Obj1 未销毁!但是同样,这也不是事实,因为当我关闭程序时,它不会报告任何内存泄漏。我很困惑。

The following code works just fine, but it shouldn't ! When I click the Button1, the object is destroyed first, and then its Value is used and I don't receive any Access Violation or something... Even more, the multiply operation gives the correct result, that proves that Obj1 is not destroyed ! But then again, this is not true either, because when I close the program it does'n report any memory leakage. I'm very confused.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  MyObj = class(TObject)
   Value: Cardinal;
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  public
   Obj1:MyObj;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
 Obj1.Free;
 Obj1.Value:=Obj1.Value * 5;
 Caption:=IntToStr(Obj1.Value);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 ReportMemoryLeaksOnShutdown:=true;
 Obj1:=MyObj.Create;
 Obj1.Value:=10;
end;

end.


推荐答案

对象已销毁。内存返回到内存管理器。接下来发生的事情是您无法控制的。内存可以返回到系统。在这种情况下,您会看到运行时错误。或者,内存管理器可以使内存保持活动状态,以备下次程序请求该大小的块重用时使用。这就是这里发生的情况。

The object is destroyed. The memory is returned to the memory manager. What happens next is out of your control. The memory could be returned to the system. In which case you'd see a runtime error. Or, the memory could be kept alive by the memory manager ready to reuse the next time the program asks for a block of that size. This is what happens here.

您的程序显示出不确定的行为。任何事情都可能发生,包括该程序似乎正常运行。显然,程序是错误的,在对象被销毁后,您不能再访问它们。

Your program exhibits undefined behaviour. Anything could happen, including the program appearing to work. Obviously the program is wrong and you must not access objects after they have been destroyed.

如果使用FastMM的完整调试版本,则应该看到错误,因为在这种情况下,采取了一些步骤来检测释放后的访问。这是一个有用的调试工具。

If you use the full debug version of FastMM then you should see an error because in that scenario steps are taken to detect access after free. That's a useful debugging tool.

这篇关于如果销毁对象后使用它,为什么我没有收到异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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