You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran容器类超出作用域时是否自动调用所含对象的析构函数?

Fortran中包含带析构函数组件的类型对象销毁时的自动析构行为

好问题!在Fortran里,你完全不需要手动在box_class的析构函数中调用glass_destructor——编译器会自动帮你处理组件的析构过程,这是Fortran finalization机制的核心特性之一。

关键规则说明

Fortran的finalization(析构)是递归触发的:

  • 当一个派生类型对象(比如你的box_class实例)超出作用域被销毁时,编译器会先自动处理它的所有组件。只要组件类型定义了finalizer(比如glass_class的glass_destructor),对应的析构函数就会被调用。
  • 所有组件的析构完成后,如果包含它们的类型(box_class)自己也定义了finalizer,才会接着调用这个类型的析构函数。

针对你的代码场景:
当box_class的对象退出作用域时,编译器会自动调用cup1和cup2的glass_destructor(组件之间的调用顺序通常由编译器实现定义,但可以保证两个都会被执行),不需要你在box_class的任何地方手动触发。

验证示例代码

你可以用这段简单的代码验证这个行为:

module glass_mod
  implicit none

  type :: glass_class
  contains
    final :: glass_destructor
  end type glass_class

contains

  subroutine glass_destructor(this)
    type(glass_class), intent(inout) :: this
    print *, "✅ 调用glass类的析构函数"
  end subroutine glass_destructor

end module glass_mod

module box_mod
  use glass_mod
  implicit none

  type :: box_class
    type(glass_class) :: cup1
    type(glass_class) :: cup2
  end type box_class

end module box_mod

program test_finalization
  use box_mod
  implicit none

  type(box_class) :: my_box

  print *, "📦 Box对象已创建,即将超出作用域..."

end program test_finalization

运行这段代码,你会看到两次✅ 调用glass类的析构函数的输出,证明两个glass_class组件的析构函数被自动调用了。

额外提示

如果之后你给box_class也添加了finalizer,它会在两个glass_class组件的析构函数都执行完毕后才被调用。比如:

type :: box_class
  type(glass_class) :: cup1
  type(glass_class) :: cup2
contains
  final :: box_destructor
end type box_class

subroutine box_destructor(this)
  type(box_class), intent(inout) :: this
  print *, "📦 调用box类的析构函数"
end subroutine box_destructor

此时程序输出顺序会是两次glass的析构,再一次box的析构。

内容的提问来源于stack exchange,提问作者EMiller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:17:03