我今天正在测试一些东西,我注意到即使没有创建实例,您也可以访问对象的 bool 类型属性。这怎么可能?当尝试修改 bool 属性时,会引发 AV。
unit Unit4;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TTest = class(TObject)
public
bBool : Boolean;
end;
TForm4 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
implementation
{$R *.dfm}
procedure TForm4.FormCreate(Sender: TObject);
var t : TTest;
begin
if t.bBool then
ShowMessage('what????');//this message is showed
t.bbool := false; //AV...
end;
end.
最佳答案
对象引用类型的局部变量(例如 t
变量)未初始化。它们包含进入函数时堆栈或关联寄存器中出现的任何值。您的 t
变量未初始化。
显然,在您的测试中,t
中的值恰好引用了程序地址空间内的某个位置,但该内存区域是只读的。你可以读它,但不能写它。在其他情况下,该地址可能不在您的进程的地址空间中,在这种情况下,即使读取该值也会导致访问冲突。
在其他情况下,该地址可能既可读又可写,然后您将被允许向该位置写入您想要的任何值。由于您写入该位置的数据,您的程序稍后可能会发生奇怪的事情;该位置可能由程序的其他部分拥有。
关于Delphi - 即使尚未创建对象, bool 属性也可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16151670/