问题描述
雷米·勒博(Remy Lebeau)无法保证访问nil指针将引发异常。这是未定义的行为。任何事情都可能发生。可能会引发异常,或者您可能只是读取垃圾,或者您可能会浪费内存,或者...。怎么会?
在这种情况下,访问NIL对象的方法不会引发AV并导致内存损坏吗?
Remy Lebeau stated that "There is no guarantee that accessing a nil pointer will raise an exception. It is undefined behavior. Anything could happen. An exception might be raised, or you might just read garbage, or you might trash memory, or ...". How come?In which circumstances, accessing the methods of a NIL object will NOT raise an AV AND lead to memory corruption?
// (Obj is any kind of object. Let's say TStringList)
Obj = nil;
Obj.LoadFromFile();
推荐答案
是。
但是,实际行为取决于实际代码。
However, the actual behavior depends on the actual code.
如果您调用动态或虚拟方法,并且在调用时会引发异常尝试直接访问实例字段。
Exception will be raised if you call dynamic or virtual methods and when you try accessing the instance fields directly.
在 nil
引用上调用静态方法并测试<$是非常安全的c $ c> Self 在其中的 nil
。
It is perfectly safe to call static method on nil
reference and testing Self
for nil
inside it.
最好的例子是静态方法是免费
。
The best example of such static method is Free
.
procedure TObject.Free;
begin
if Self <> nil then
Destroy;
end;
很明显,以上行为已得到很好的定义,否则以前编写的每个Delphi程序都会随机崩溃(或时间)。
Obviously, above behavior is well defined, otherwise every Delphi program ever written would crash randomly (or all the time).
通常,访问 nil
引用的字段将导致崩溃。从理论上讲,足够大的类是可能的。
In general, accessing fields of nil
reference will result in crash. In theory with large enough class anything is possible.
David Heffernan提供的示例类
Example class provided by David Heffernan
type
TSillyExample = class
FStuff: array [0..SomeVeryLargeNumber-1] of Byte;
FAreYouFeelingLucky: string;
end;
这篇关于是否可以保证访问nil指针会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!