使用未在数组赋值中分配的可分配数组

Use an allocatable array that is not allocated in an array assignment

在 Fortran 中,如果我使用未在数组赋值中分配的可分配数组,我预计会出现一些运行时错误。 但事实证明,可分配数组是在分配期间分配的。这似乎是一个危险的设计。有人可以解释这种设计的原因吗?示例代码如下:

module yj_mod
 real,dimension(:,:),allocatable :: den_i_right
end module yj_mod

program main
  call p()
end program main

subroutine p()
  use yj_mod,only : den_i_right
  implicit none
  real :: a(3,4)
  a=3.0
  den_i_right=a
write(*,*) size(den_i_right,1), size(den_i_right,2)
end subroutine p

我用gfortran编译了上面的代码。 运行 代码表明 den_i_right 成为与 a

相同形状的数组

它被非正式地称为 (..... wait it .....) (re-)allocation on assignment。来自 Fortran 2003 标准的特定语言使用 variable=expr

"If variable is an allocated allocatable variable, it is deallocated if expr is an array of different shape or any of the corresponding length type parameter values of variable and expr differ. If variable is or becomes an unallocated allocatable variable, then it is allocated with each deferred type parameter equal to the corresponding type parameters of expr, with the shape of expr, and with each lower bound equal to the corresponding element of LBOUND(expr)."