根据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在finalization之后打印
这种奇怪的行为是由某些 ifort 错误引起的,还是由错误应用 finalization FORTRAN 2003 功能引起的,我做错了什么?