Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Fortran最终例程在变量超出范围之前调用自身_Fortran_Destructor_Final_Intel Fortran - Fatal编程技术网

Fortran最终例程在变量超出范围之前调用自身

Fortran最终例程在变量超出范围之前调用自身,fortran,destructor,final,intel-fortran,Fortran,Destructor,Final,Intel Fortran,我对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

我对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编译的,

没有任何错误(2013年Fortran 2003代码使用固定格式源代码延续)

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

第二个调用是完成函数结果(从概念上讲,在表达式中使用该结果的值并将其传输到赋值的左侧之后)


在程序终止之前存在的实体(此处通过执行end program语句)没有最终确定。

Ok,我得到构造函数按值返回对象,因此它也调用析构函数。但是由于
参数
的析构函数不会在程序结束时调用,那么为它可能拥有的任何可分配成员(或派生成员)释放内存呢?编译器会解决这个问题吗?好吧,我举了一个小例子,似乎是的,它解决了。虽然在执行顺序方面有一些共同的方面和要求,但终结和“自动释放”不是一回事。在这两种情况下,程序结束和过程结束或块构造结束之间的终结和解除分配行为都有所不同。此外,在程序终止之前不需要解除分配。最近一个在gfortran中启用终结功能的补丁程序禁用了程序端的自动解除分配,以便不调用终结功能。@IanH如果您在声明的类型
my_type
中有指针(如链表),编译器将不会自动解除分配,既然在程序终止时没有执行终结例程,那么在这种情况下终结有什么意义呢?