取消分配 Fortran 派生类型是否也会自动取消分配成员数组和指针? [英] Does deallocating a Fortran derived type automatically deallocate member arrays and pointers as well?

查看:27
本文介绍了取消分配 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.

小心,您必须解除分配指针,而不仅仅是无效.取消它只会删除对已分配内存的引用.如果不释放,就会发生内存泄漏.

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 派生类型是否也会自动取消分配成员数组和指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆