关于delphi:为什么不提高EInvalidPointer?

Why not raise EInvalidPointer?

Delphi文档说明:

Never raise an EInvalidPointer exception directly. EInvalidPointer is raised internally by the memory manager.

我正在编写一个自定义基类作为TInterfacedObject的替代,尽可能地遵循RTL实现,并且通过示例看,RTL中的TInterfacedObject实现BeforeDestruction

1
2
3
4
5
procedure TInterfacedObject.BeforeDestruction;
begin
  if RefCount <> 0 then
    Error(reInvalidPtr);  
end;

其中Error(reInvalidPtr)通过RTL本地的各种单位范围方法引发EInvalidPointer

如果我正在编写自己的类,我该如何实现BeforeDestruction? 为什么不这样做?:

1
2
3
4
5
procedure TMyInterfacedObject.BeforeDestruction;
begin
  if RefCount <> 0 then
    raise EInvalidPointer.CreateRes(@SInvalidPointer) at ReturnAddress;
end;

SysUtils中声明的全局InvalidPointer异常对象有什么特别之处吗? 如果这是一个坏主意,那么在这里简单地提出一个自定义异常是否明智?


大卫回答的补充; 有关InvalidPointer的特殊内容,用于引发EInvalidPointer,以及OutOfMemory < - > EOutOfMemory,它们的上升EHeapException的文档主题中有更详细的解释:

EHeapException is the exception class for errors related to heap-allocated memory.

EHeapException's descendants—EOutOfMemory and EInvalidPointer—are used
to handle failed allocations of dynamic memory and invalid pointer
operations.

Note: Memory for these exceptions is pre-allocated whenever an application starts and remains allocated as long as the application is
running. Never raise EHeapException or its descendants directly.

我猜测的是,一旦你遇到内存问题,分配内存来创建这些错误可能不安全:因为缺乏内存或可能存在腐败......


避开原始问题,您可以避免仅使用与运行时相同的代码来询问它:

1
System.Error(reInvalidPtr);