Does deallocating a Fortran derived type automatic

2019-02-17 07:03发布

问题:

In Fortran, if I have an allocatable array of derived types, each consisting of a pointer and an allocatable array,

type group
  real, pointer :: object
  real, allocatable :: objectData(:,:)
end type group

type(group), allocatable :: myGroup(:)

would I be able to deallocate all memory contained in this type by simply making a single call

deallocate(myGroup)

or do I need to deallocate the arrays within each type first, before deallocating the derived type:

do i = 1, size(myGroup)
  nullify(myGroup(i)%object)
  deallocate(myGroup(i)%objectData)
end do

deallocate(myGroup)

I'm leaning towards option 2 and nullifying all memory before deallocating the derived type, if not just to ensure that memory leaks aren't happening, but if option 1 is equivalent then that would be useful for future reference and save me a few lines of code.

回答1:

Only allocatable components are automatically deallocated. You must deallocate pointers yourself.

Be careful, you have to deallocate the pointer, not just nullify. Nullifying it just removes the reference to the allocated memory. If you do not deallocate, a memory leak will happen.



回答2:

You know that the allocatable components are deallocated automatically but the pointers aren't. But for

would I be able to deallocate all memory contained in this type by simply making a single call

the answer is: yes (with some effort).

If the type group is finalizable then an entity of that type is finalized when it is deallocated.

type group
  real, pointer :: object
  real, allocatable :: objectData(:,:)
 contains
  final tidy_up
end type group

for the procedure

subroutine tidy_up(myGroup_array)
  type(group), intent(inout) :: myGroup_array(:)
  ! ... deallocate the pointers in the elements of the array
end subroutine

You can use this finalization to take care of the pointer components.

Finally, be aware of some subtleties. Also note that this somewhat reduces your control over whether the pointer is deallocated (there are many times you wouldn't want it to be).