检查Ada中的空指针

时间:2018-01-04 04:19:30

标签: pointers ada

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

鉴于这种情况,如何检查访问类型是否指向0x0(null)?

请考虑以下事项:

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

2 个答案:

答案 0 :(得分:7)

if myAccess = null then
...
end if;

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

答案 1 :(得分:1)

另一个可以帮助你的选项是将指针声明为“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)及其正确用法取决于您的需求。

相关问题