I have a problem with Fortran destructors/final routines. Having the code below:
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
the output is:
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
So it seems that constructed object is destructed as soon as its construction ends rather than at the end of the program. Any ideas what's wrong? Above code was compiled with ifort 14.0.0,
Nothing is wrong (bar apparent (?) use of fixed form source continuation with Fortran 2003 code in 2013).
The first "destructor" call is to finalize the left hand side of the assignment statement.
The second call is to finalize the function result (conceptually after the value of that result has been used in the expression and transferred to the left hand side of the assignment).
Entities existing immediately prior to termination of the program (here by execution of the end program statement) are not finalized.