Does the finalizer have to be elementary to be called on out-of-bounds elements of the array to be allocated?
If I have an allocable array of final type finalizable, will the finalizer be called on every single element when the array goes out of scope?
Here's a small sample code that illustrates the question:
module LeakyTypeModule
implicit none
private
type, public :: LeakyType
real, pointer :: dontLeakMe(:) => null()
contains
procedure :: New
final :: Finalizer
end type
contains
subroutine New(self, n)
class(LeakyType), intent(out) :: self
integer , intent(in) :: n
allocate(self%dontLeakMe(n))
self%dontLeakMe = 42.0
end subroutine
subroutine Finalizer(self)
type(LeakyType), intent(inout) :: self
if (associated(self%dontLeakMe)) deallocate(self%dontLeakMe)
end subroutine
end module
program leak
use LeakyTypeModule
implicit none
type(LeakyType), allocatable :: arr(:)
allocate(arr(1))
call arr(1)%New(1000)
deallocate(arr)
end program
Note that this program loses the array dontLeakMe
allocated in the method New()
LeakyType
. This was a bit of a surprise to me at first, but then I found that the problem could be fixed by declaring a finalizer elemental
. Both gfortran and ifort behave the same, so I assume that this behavior is in accordance with the Fortran 2003 standard.
Can anyone confirm this? To be honest, I find it difficult to understand what is being said in this particular question.
Currently, I also don't see much point in not declaring all my finalizers elemental. Does this have any app that I am missing?
source to share
The rules for determining whether the final procedure is called and which final procedure is called are the same as for resolving general procedures in terms of rank matching requirements.
Noting that the question is tagged Fortran 2003 ...
Elementary routines in Fortran 2003 and earlier must be PURE. If your finalizer needs to do something that is incompatible with a pure attribute (which is common enough), then the finalizer cannot be rudimentary and you need to write rank related options.
Fortran 2008 introduces the concept of IMPURE ELEMENTAL, which is great for writing finalizers.
source to share