Hey Folks,
I want to double-check an assumption I have for a type bound procedure function that returns a pointer, pointing to an attribute of the type.
Assume we have this type holding a concatenated array:
module array_test
type :: array_concat
integer, allocatable :: arrays(:)
integer, allocatable :: offset(:)
integer, allocatable :: length(:)
contains
procedure :: view
end type array_concat
contains
function view(this, index) result(array)
class(array_concat), target, intent(in) :: this ! note target attribute
integer, intent(in) :: index
integer, pointer :: array(:)
integer :: first, last
first = this%offset(index)
last = first + this%length(index) - 1
array => this%arrays(first:last)
end function view
end module array_test
I know that within view it is valid to put a target attribute on the class dummy argument and then point to attributes of this.
In order for the pointer to be valid after the function return, the type instance needs to be a valid target, like this:
program array_prog
use array_test, only: array_concat
implicit none
type(array_concat), target :: ac
integer, pointer :: arr(:)
ac%arrays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ac%offset = [1, 4, 7]
ac%length = [3, 3, 4]
! point to the second sub-array (elements 4, 5, 6)
arr => ac%view(2)
end program array_prog
Now my question:
When the instance is not a valid target, I think, I can still use view to get a copy of the desired array with this:
program array_prog
use array_test, only: array_concat
implicit none
type(array_concat) :: ac ! no target
integer, allocatalbe :: arr(:) ! allocatable instead of pointer
ac%arrays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ac%offset = [1, 4, 7]
ac%length = [3, 3, 4]
! COPY the second sub-array (elements 4, 5, 6)
arr = ac%view(2) ! implicit allocation
end program array_prog
The function should allocate the LHS arr before the returned pointer get disassociated (I know some compilers would still allow a pointer to be valid after return (arr => ac%view(2)), but by the standard, ac is not a target, so I can’t / shouldn’t point to attributes of it).
Is this right? If so, this would be great to have a dual-use of the view function (either associating a pointer of creating a copy).
Cheers,
Sebastian