当我们编译(gfortran 5.3或7.2)并运行以下代码时,main.f03的第9行最终会在一个永远不会被调用的子例程中。任何人都可以解释原因吗?
main.f03:
program main
use minimalisticcase
implicit none
type(DataStructure) :: data_structure
type(DataLogger) :: data_logger
call data_structure%init()
call data_logger%init(data_structure)
end program
minimalisticcase.f03:
module minimalisticcase
implicit none
type, public :: DataStructure
integer :: i
contains
procedure, pass :: init => init_data_structure
procedure, pass :: a => beginning_of_alphabet
end type
type, public :: DataLogger
type(DataStructure), pointer :: data_structure
contains
procedure, pass :: init => init_data_logger
procedure, pass :: do_something => do_something
end type
contains
subroutine init_data_structure(self)
implicit none
class(DataStructure), intent(inout) :: self
write(*,*) 'init_data_structure'
end subroutine
subroutine beginning_of_alphabet(self)
implicit none
class(DataStructure), intent(inout) :: self
write(*,*) 'beginning_of_alphabet'
end subroutine
subroutine init_data_logger(self, data_structure)
implicit none
class(DataLogger), intent(inout) :: self
class(DataStructure), target :: data_structure
write(*,*) 'init_data_logger'
self%data_structure => data_structure
call self%do_something()
end subroutine
subroutine do_something(self)
implicit none
class(DataLogger), intent(inout) :: self
write(*,*) 'do_something'
end subroutine
end module
在'minimalisticcase.f03'的第40行,我们称之为DataLogger的'do_something'。但是,执行DataStructure的'beginning_of_alphabet'子程序!
显然,可以通过将'minimalisticcase.f03'中的第13行从type(DataStructure), pointer :: data_structure
更改为class(DataStructure), pointer :: data_structure
来解决此问题。
但为什么?
答案 0 :(得分:3)
这是gfortran中的一个错误。我将其作为https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82312发布在Bugzilla上。现在,错误已在GCC主干上修复。
临时解决方法是将指针赋值包含在选择类型中,因此:
select type (data_structure)
type is (DataStructure)
self%data_structure => data_structure
end select