我有一个解析文本文件的对象。这是我的主要程序:
program main
use Parser_class
implicit none
type(Parser) :: Parser
call Parser%ProcessFile('data.txt')
call Parser%Deallocate
end program main
其中类型定义是
module Parser_class
type :: Parser
contains
procedure, public :: ProcessFile
procedure, public :: Deallocate
end type Parser
contains
subroutine ProcessFile(self)
...
end subroutine
subroutine Deallocate(self)
class(Parser) :: self
...
end subroutine
end module Parser_class
我读到了 Final 关键字并将类型定义更改为
module Parser_class
type :: Parser
contains
procedure, public :: ProcessFile
final :: Deallocate
end type Parser
contains
subroutine ProcessFile(self)
...
end subroutine
subroutine Deallocate(self)
type(Parser) :: self
...
end subroutine
end module Parser_class
另外,在主程序中我没有call Parser%Deallocate
不再了。现在任何时候都不会调用终结器。我不知何故明白这是因为我从不破坏或覆盖Parser
目的。但我该如何做到这一点,或者处理释放过程的正确方法是什么?
In the Fortran 2008 standard, when finalization comes about is given in section 4.5.6.31. I won't copy all the times here, but I will summarize.
下面明确提到的是何时,何时不:
如果图像执行因错误(例如分配失败)或因执行 stop-stmt、error-stop-stmt 或 end-program-stmt 而终止,则终止前立即存在的实体不会最终确定。
这涵盖了您的程序。Parser
位于程序范围内,并且在程序结束时仍然存在。没有明显的其他因素会导致最终确定。
If Deallocate
是该类型的最终过程,那么该类型的对象的最终化与类型绑定过程的调用有一些微妙的不同。在最终确定中,该过程是递归的:组件和父级本身也受到最终确定的影响。对于子例程调用,递归必须以某种方式手动出现。
在许多情况下,人们并不关心实体在程序结束时是否最终确定。毕竟,任何释放都是操作系统的问题,而不是程序员的问题。然而,有时确实需要其他形式的整理。
真正的最终确定可以通过某些方式强制进行。如果检查下面的列表,我会想到两个选项:
- 使
Parser
对象可分配并显式释放它;
- 将整个事情包裹在一个
block
构造。
粗略地总结一下何时完成:
- 当有释放时(指针或可分配);
- 作为程序启动
intent(out)
论据;
- 对于未保存的本地对象,当到达可执行结构或子程序的末尾时;
- 就在对变量进行内部赋值之前;
- 函数结果值结束后。
1If you aren't reading the final form of the document you'll want to pretend paragraphs 5 and 7 don't exist.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)