I have a derived type t_file with a finalization routine close which simply writes “Finalization” to the screen.
There is also a function returning an instance of the type t_file.
The output of this program is
Finalization.
Finalization.
Just opened
2000
Done.
I have two questions:
- Why does the finalization occur before the
Just openedoutput? - Why does the finalization occur twice?
My compiler is Intel(R) Visual Fortran Composer XE 2011 12.1.3526.2010.
Here is the code:
module m_file
implicit none
type t_file
integer::iu=1000
contains
final::close
end type
contains
function openFile() result(f)
implicit none
type(t_file)::f
f%iu = 2000
end function
subroutine close(this)
implicit none
type(t_file)::this
write(*,*) 'Finalization.'
end subroutine
end module
program foo
use m_file
implicit none
type(t_file)::f
f = openFile()
write(*,*) 'Just opened'
write(*,*) f%iu
write(*,*) 'Done.'
read(*,*)
end program
This behaviour surprised me too. I’ve been getting to grips with Fortran’s new(-ish) OO features but haven’t yet needed to write final procedures. I think that I can provide an explanation, of sorts, for this behaviour.
On p282 of Modern Fortran Explained the authors write:
It looks to me as if you are hitting both of the two cases mentioned in this paragraph. You get the first
Finalizationwhen the entity namedfinside the functionopenFileis about to go out of scope on return from that function.You get the second
Finalizationwhen the variablefin the program scope is used on the lhs of the assignmentf = openFile().From all of this I conclude that you are not seeing premature finalisation of
fin the program scope, but something subtly different.I’m not entirely convinced that this is what is happening, and I cannot think of a good reason why the language’s behaviour should be as it is. I’m a bit surprised, now that I’ve looked into it, that you don’t get a third
Finalizationmessage as the program ends andfgoes out of scope.With any luck a real Fortran guru will come past soon and enlighten us all.