【问题标题】:Why Access Violation here?为什么在这里访问冲突?
【发布时间】:2012-07-23 17:17:04
【问题描述】:

我正在尝试在一些 Delphi 项目中构建自己的类。代码是这样的:

type
 TMyClass = class(TObject)
private
 hwnMain, hwnChild: HWND;
 Buffer, URL: string;
 Timer: TTimer;
public
 procedure ScanForClass;
end;

var
Form1: TForm1;
TimerAccess: TMyClass;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
 TimerAccess.ScanForClass;
end;

procedure TMyClass.ScanForClass;
begin
 Timer:= TTimer.Create(Application); **here I get Access Violation!!**
 Timer.Interval:= 5000;
 Timer.Enabled:= true;

为什么会出现访问冲突?

【问题讨论】:

    标签: delphi


    【解决方案1】:

    您的代码在使用之前不会创建该类的实例。

    所以它会在这段代码中引发访问冲突异常:

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      TimerAccess.ScanForClass;
    end;
    

    因为 TimerAccess 仍未初始化(未定义)。

    在FormCreate中,调用构造函数并将实例赋值给变量

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      TimerAccess := TMyClass.Create; 
      TimerAccess.ScanForClass;
    end;
    

    在FormDestroy中,调用析构函数进行清理:

    procedure TForm1.FormDestroy(Sender: TObject);
    begin
      TimerAccess.Free;
    end;
    

    注意:如果 TForm1 的实例很多,代码将不起作用,因为变量 TimerAccess 是全局的,并且每个 Form 实例都会在 FormCreate 中分配一个新的 TMyClass 实例,从而导致内存泄漏。一种解决方案是使 TimerAccess 成为 Form 类的属性(或字段)。

    【讨论】:

    • 作为替代方案,如果希望创建此表单的多个实例,则有两种选择:将TimerAccess 移动到表单的类中,或移动TimerAccess 的构造/销毁进入本单元底部的InitializationFinalization 部分。
    猜你喜欢
    • 1970-01-01
    • 2015-08-25
    • 2014-11-23
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多