【问题标题】:gfortran destructor of membersgfortran 成员的析构函数
【发布时间】:2019-03-09 16:36:09
【问题描述】:

我注意到 gfortran (GNU Fortran (Debian 4.9.2-10) 4.9.2) 的一个奇怪的链接错误取决于我在派生类型中定义成员的顺序。使用 ifort (ifort (IFORT) 18.0.1 20171018),代码编译并按预期运行。

module bug

  implicit none
  type indestructable
    integer :: i
  end type
  type destructable
    integer :: i
  contains
    final :: destruct
  end type destructable

  type compound
    type(destructable) :: des
    type(indestructable) :: ind
  end type compound

contains

  subroutine destruct(instance)

    type(destructable), intent(in) :: instance
    write(*,*) instance%i

  end subroutine destruct

  subroutine run

    type(compound) :: cmp

    cmp%des%i = 3
    cmp%ind%i = 4

  end subroutine run

end module bug

program main
  use bug, only: run
  implicit none
  call run
end program main

这个程序在结束时应该打印出 '3',因为 'cmp' 中的 'des' 有一个析构函数可以写出它的成员 'i',它被设置为 3。

在 gfortran 中,编译器会给出一个错误,即未定义复合类型的析构函数。这个析构函数应该自动生成并调用所有成员的析构函数。问题是复合类型中还有一个没有析构函数的类型的成员。这在某种程度上阻碍了 gfortran 与析构函数的组织。

通过将可破坏成员放在不可破坏成员之后(在复合类型定义内切换两行)来解决此问题。

有谁知道这是一个编译器问题,可以在以后的版本中解决,还是我做错了什么,ifort 以某种方式为我修复了它。我一直都知道,定义成员变量的顺序并不重要。

对于遇到相同问题的任何人:“始终将可破坏的成员放在最后”。然而,非派生类型似乎并不重要,即使它们是可分配的。

【问题讨论】:

  • 可能是上述版本中的错误(GCC 4.9.2 发布 [2014-10-30]),我在 Windows 上尝试使用 gfortran 7.3.0(所以没有真正的可比性),但我没有'没有看到问题。
  • gfortran 据说还没有fully support finalization
  • gfortran 中主要没有最终确定的是函数结果,但这里没有用到。

标签: fortran gfortran derived-types


【解决方案1】:

这很可能是bug 58175,已在 GCC 7 中解决。更新您的 GCC。我可以确认你的代码在这个版本中编译。

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 2016-01-29
    • 2021-11-19
    • 2015-05-14
    • 2018-05-13
    • 2011-01-16
    • 2014-06-08
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多