如果我有一个可终结的派生类型的可分配数组,当数组超出范围时,是否会在每个单独的元素上调用终结器?
这是一个小代码示例,说明了这个问题:
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
请注意,此程序泄漏 LeakyType
New()
方法中分配的 dontLeakMe
数组 . 起初这对我来说有点令人惊讶,但后来我发现问题可以通过声明终结器 elemental
来解决 . gfortran和ifort都以相同的方式运行,所以我认为这种行为遵循Fortran 2003标准 .
谁能证实这一点?说实话,我很难理解标准在这一点上所说的内容 .
现在我也没有看到很多用途,没有宣布我的所有终结者元素 . 这有什么应用我忽略了吗?
1 回答
确定是否调用最终过程以及调用哪个最终过程的规则与根据等级匹配要求解决通用过程的规则相同 .
注意到这个问题被标记为Fortran 2003 ...
Fortran 2003及之前的元素程序必须是PURE . 如果你的终结器需要做一些与pure属性不相容的东西(这是相当常见的),那么终结器不能是元素的,你需要编写特定于等级的变体 .
Fortran 2008引入了IMPURE ELEMENTAL的概念,这对于编写终结器非常方便 .