Zero Size for Access Types


Zero size for access types are to emphasize that the access type shouldn't be used for anything
other than satisfying the need to have a named type (for the return type of
a function).

For example, in the stack-with-limited-items:

  generic
    type Item_Type is limited private;
  package Stacks is

    type Stack_Type is limited private;

    type Item_Access is access all Item_Type;
    for Item_Access'Storage_Size use 0;

    function Push (Stack : access Stack_Type) return Item_Access;

    function Set_Top (Stack : access Stack_Type) return Item_Access;

    ...
  end Stacks;


An Ada function declaration must return a named type, so I have to declare
an access type for the return type.  But I only want clients to do this:

    Stack : aliased Stack_Type;
  begin
    Push (Stack'Access).all := Value;
    ...
    Set_Top (Stack'Access).all := Value;


A client doesn't ever declare an object of type Item_Access -- that type
just happens to be the type returned by the function, which you always
dereference immediately.

Setting the Storage_Size for the access type ensures that no storage
resources are allocated for the type, and it prevents you from using it to
allocate, ie

  IA : Item_Access := new Item_Type'(Value);  -- you're being bad

A good compiler will give you a warning at compile-time that the allocator
will raise Storage_Error at run-time.  (Sadly, there's no way to statically
prevent allocator use.)

The main thing is that the type is there just to satisfy the requirement for
a named type, and to ensure that no storage resources are consumed
unnecessarily.

Contributed by: Matthew Heaney
Contributed on: September 10, 1999
License: Public Domain

Back