3

我对 Fortran 析构函数/最终例程有疑问。拥有以下代码:

  module my_type_module
    implicit none

    type my_type
      contains
        final :: destructor
    end type my_type

    interface my_type
      ! Constructor declaration
      module procedure my_type_constructor
    end interface my_type

    contains
      function my_type_constructor()
        type(my_type) :: my_type_constructor

        print *, 'In constructor address is: ',
 &          loc(my_type_constructor)

      end function my_type_constructor

      subroutine destructor(this)
        type(my_type) :: this
        print *, 'Destructor of my_type object with address: ',
 &        loc(this)
      end subroutine destructor

  end module my_type_module

  program trial

    use my_type_module
    implicit none

    type(my_type) :: argument

    print *, 'Trial program starts'
    print *, 'Initial address is', loc(argument)

    argument = my_type_constructor()

    print *, 'Address afer constructor is called is', loc(argument)

    print *, 'doing some work...'
    print *, 'finishing program...'

    print *, 'Final address is', loc(argument)

  end program trial

输出是:

Trial program starts
Initial address is            4351590240
In constructor address is:        140734743834256
Destructor of my_type object with address: 4351590240
Destructor of my_type object with address: 140734743834256
Address afer constructor is called is      4351590240     
doing some work...
finishing program...
Final address is            4351590240

因此,似乎构造的对象在其构造结束时而不是在程序结束时被破坏。有什么想法有什么问题吗?上面的代码是用 ifort 14.0.0 编译的,

4

1 回答 1

2

没有任何问题(很明显(?)在 2013 年使用 Fortran 2003 代码的固定形式源代码延续)。

第一个“析构函数”调用是为了完成赋值语句的左侧。

第二个调用是完成函数结果(概念上是在该结果的值已在表达式中使用并转移到赋值左侧之后)。

在程序终止之前存在的实体(这里通过执行结束程序语句)没有最终确定。

于 2013-10-21T03:25:20.090 回答