【发布时间】:2015-03-13 10:58:22
【问题描述】:
根据Fortran Wiki,intel fortran 编译器版本 14 应支持 FORTRAN 2003 标准中定义的终结。我尝试将此功能与 ifort 14 一起使用,但观察到了奇怪的行为。以下示例应显示:
module mtypes
implicit none
type mytype
integer, private :: nr
contains
final :: delete_mytype
procedure :: print_mytype
end type
contains
!> \brief Constructs a new mytype
!! \return The created mytype
!>
function init_mytype(number)
type(mytype) :: init_mytype
integer, intent(in) :: number
! allocate(init_mytype)
init_mytype = mytype(number)
print *, 'init mytype', number
end function
!> \brief De-constructs a mytype object
!>
subroutine delete_mytype(this)
type(mytype) :: this !< The mytype object that will be finalized
print *, 'Deleted mytype!', this%nr
end subroutine delete_mytype
!> \brief Print something from mytype object
!>
subroutine print_mytype(this)
class(mytype) :: this !< The mytype object that will print something
print *, 'Print something from mytype!', this%nr
end subroutine print_mytype
end module mtypes
program main
use mtypes
type(mytype) :: t1, t2
call t1%print_mytype()
call t2%print_mytype()
t1 = mytype(1)
call t1%print_mytype()
t2 = init_mytype(2)
call t2%print_mytype()
end program main
在这个完整的例子中,type mytype 被定义为只有一个值nr。这种类型可以使用简单的类型构造函数来创建,例如mytype(1) 或初始化函数init_mytype。还定义了一个子例程print_mytype,它简单地将mytype%nr 打印到标准输出。最后,final 例程 delete_mytype 应该用于最终确定,尽管在本例中它只将一些信息打印到标准输出。
此示例给出以下输出:
Print something from mytype! 0
Print something from mytype! 0
Deleted mytype! 0
Print something from mytype! 1
Deleted mytype! -2
init mytype 2
Deleted mytype! 0
Deleted mytype! 2
Print something from mytype! 2
- 第 1 行:好的,t1 初始化为默认值 0
- 第 2 行:好的,t2 初始化为默认值 0
- 第 3 行:好的,分配新对象
t1%mytype(1)后,旧版本被删除 - 第 4 行:好的,带有
nr = 1的版本已打印 - 第 5 行:奇怪,
nr=-2的版本是从哪里来的? - 第 6 行:好的,带有
nr = 2的版本已初始化 - 第 7 行:好的,分配新对象
t2 = init_mytype(2)后,旧版本被删除 - 第 8 行:奇怪,t2 在调用
t2%print_mytype()之前完成 - 第 9 行:奇怪,t2 在定稿后打印
这种奇怪的行为是由某些 ifort 错误引起的,还是由于错误应用了终结 FORTRAN 2003 功能而我做错了什么?
【问题讨论】:
-
最好在类型定义中设置一个默认值
integer, private :: nr = 0,而不是依赖编译器完成的自动初始化。话虽如此,据我所知,ifort 默认将所有整数初始化为零,所以我不确定是什么导致了这些问题。在我的机器上,它在第 5 行打印零。
标签: fortran intel-fortran fortran2003