本文介绍了释放 Fortran 派生类型是否也会自动释放成员数组和指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Fortran 中,如果我有一个派生类型的可分配数组,每个类型由一个指针和一个可分配数组组成,

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)

我倾向于选项 2 并在释放派生类型之前使所有内存无效,如果不仅仅是为了确保不会发生内存泄漏,但如果选项 1 是等效的,那么这将有助于将来参考并拯救我几行代码.

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.

推荐答案

只有可分配的组件会被自动释放.您必须自己释放指针.

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

小心,你必须deallocate指针,而不仅仅是nullify.取消它只会删除对分配内存的引用.如果不解除分配,就会发生内存泄漏.

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.

这篇关于释放 Fortran 派生类型是否也会自动释放成员数组和指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:25