我遇到Fortran析构函数/最终例程的问题。 有下面的代码:
module my_type_module
implicit none
type my_type
contains
final :: destructor
end type my_type
interface my_type
! Constructor declaration
module procedure my_type_constructor
end interface my_type
contains
function my_type_constructor()
type(my_type) :: my_type_constructor
print *, 'In constructor address is: ',
& loc(my_type_constructor)
end function my_type_constructor
subroutine destructor(this)
type(my_type) :: this
print *, 'Destructor of my_type object with address: ',
& loc(this)
end subroutine destructor
end module my_type_module
program trial
use my_type_module
implicit none
type(my_type) :: argument
print *, 'Trial program starts'
print *, 'Initial address is', loc(argument)
argument = my_type_constructor()
print *, 'Address afer constructor is called is', loc(argument)
print *, 'doing some work...'
print *, 'finishing program...'
print *, 'Final address is', loc(argument)
end program trial
输出是:
Trial program starts
Initial address is 4351590240
In constructor address is: 140734743834256
Destructor of my_type object with address: 4351590240
Destructor of my_type object with address: 140734743834256
Address afer constructor is called is 4351590240
doing some work...
finishing program...
Final address is 4351590240
因此,似乎构造对象在构造结束时而不是在程序结束时被破坏。 有什么想法有什么不对吗? 上面的代码是用ifort 14.0.0编译的,
答案 0 :(得分:1)
没有错(明显(?)在2013年使用固定格式源继续使用Fortran 2003代码。)
第一个“析构函数”调用是完成赋值语句的左侧。
第二个调用是最终确定函数结果(概念上,在表达式中使用了该结果的值并将其传送到赋值的左侧)。
在程序终止之前存在的实体(此处执行结束程序声明)尚未最终确定。