为什么不提高 EInvalidPointer?

Why not raise EInvalidPointer?

Delphi documentation states :

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

我正在编写自定义基础 class 作为 TInterfacedObject 的替代方案,尽可能遵循 RTL 实现,并通过示例查看 TInterfacedObject 在RTL 将 BeforeDestruction 实现为:

procedure TInterfacedObject.BeforeDestruction;
begin
  if RefCount <> 0 then
    Error(reInvalidPtr);  
end;

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

如果我自己编写 class,我应该如何实现 BeforeDestruction?为什么不这样做呢? :

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

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

回避原问题,只需使用与运行时相同的代码即可避免提问:

System.Error(reInvalidPtr);

; what's special about InvalidPointer, which is used to raise an EInvalidPointer, together with OutOfMemory <-> EOutOfMemory is explained in more detail in the documentation topic for their ascendant 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.

我想这相当于,一旦内存出现问题,分配内存来创建这些错误可能是不安全的:因为缺少内存或可能损坏...