释放Fortran派生类型是否会自动释放成员数组和指针? [英] Does deallocating a Fortran derived type automatically deallocate member arrays and pointers as well?
问题描述
类型组
real,pointer :: object
real,allocatable :: objectData(:, :)
结束类型组
$ b类型(组),allocatable :: myGroup(:)
我可以通过简单地将单个内存中的所有内存解除分配请致电
取消分配(myGroup)
还是需要在释放派生类型之前首先释放每个类型中的数组:
nullify(myGroup(i)%object)
deallocate(myGroup(i)%objectData)
end do
解除分配(myGroup)
在取消分配派生类型之前,我倾向于选项2并取消所有内存,如果不仅仅是为了确保内存泄漏不会发生,但是如果选项1是相同的那么这对于将来的参考很有用,并且保存我几行代码。
只有可分配组件会自动释放。您必须自己释放指针。
请注意,您必须释放指针,而不是 nullify 。取消它只是删除对分配内存的引用。如果你不释放,会发生内存泄漏。
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.
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屋!