-
Notifications
You must be signed in to change notification settings - Fork 19
Description
With the generic features planned for Fortran 202Y we might have a chance to design robust containers (lists, dictionaries, etc.) for Fortran. One thing, which is still missing for this aim, is the possibility to reliably return a pointer to an already stored item. (Especially useful, when big items are stored.) Reliably means, that you get a compiler error, if you try to extract the pointer in an "unsafe" way.
Currently, to get a pointer to a stored item, you could use following scheme:
type :: list
type(item_type), allocatable :: content(:)
contains
procedure :: view
end type list
function view(this, ind) result(itemptr)
class(list), target, intent(in) :: this
integer, intent(in) :: ind
type(item_type), pointer :: itemptr
itemptr => this%content(ind)
end function viewThe problem here is, that if the user forgets to define the target attribute for the list instance, there is no warranty, that the returned pointer is valid and there will be no compiler error (or even warning). Alternatively, one could declare content as a pointer instead of an allocatable. The pointer were then warrantedly valid (even without the target attribute for the dummy argument this ), but this opens several other issues typical for allocated pointer components (automatic deallocation or behavior on assignment might be tricky...)
An alternative would be to allow for the pointer attribute for the formal argument of the instance in the type bound procedure (provided, the formal argument is intent(in)):
type :: list
type(item_type), allocatable :: content(:)
contains
procedure :: view
end type list
function view(this, ind) result(itemptr)
! Note pointer attribute
class(list), pointer, intent(in) :: this
integer, intent(in) :: ind
type(item_type), pointer :: itemptr
itemptr => this%content(ind)
end function viewWhen the function is called, the compiler should then ensure, that the actual instance on the caller's side has either the pointer or the target attribute. This would make sure that the returned pointer is warranted to be valid outside of the scope of the view() function.