在 Ada 中检查空指针

Checking for Null Pointer in Ada

一般来说,如果您尝试取消引用空指针(访问类型),Ada 将引发 Constraint_Error。但是,例如,如果您使用了 pragma Suppress (all_checks),此行为将被禁用。

在这种情况下,如何检查访问类型是否指向 0x0(空)?

考虑以下几点:

type My_Access_Type is access all My_Type'Class;

procedure myProcedure ( myAccess : in My_Access_Type ) is
begin

-- need to have check in here
end
if myAccess = null then
...
end if;

虽然不一定指向0x0。访问类型不是指针,可能以不同于普通地址的方式实现。

另一个可以帮助您的选项是将指针声明为 "not null"。

type My_Access is not null access My_Type;

这可以防止声明未初始化的 My_Access 类型。

X : My_Access; -- compile error

此解决方案存在一些缺点(请参阅 https://en.wikibooks.org/wiki/Ada_Programming/Types/access#Null_exclusions),其正确用法取决于您的需要。