Memory management 在Fortran中用析构函数释放内存

Memory management 在Fortran中用析构函数释放内存,memory-management,constructor,fortran,valgrind,destructor,Memory Management,Constructor,Fortran,Valgrind,Destructor,基础:我正在尝试用Fortran编写好的代码,使用构造函数和析构函数。 下面是一个非常简单的Test类及其客户端的示例: module test_class_module implicit none type :: Test private integer, allocatable :: arr(:) CONTAINS final :: destructor end type interface Test procedure :: constructor end inter

基础:我正在尝试用Fortran编写好的代码,使用构造函数和析构函数。 下面是一个非常简单的
Test
类及其客户端的示例:

module test_class_module
implicit none

type :: Test
private
integer, allocatable :: arr(:)
 CONTAINS
    final :: destructor
end type

interface Test
    procedure :: constructor
end interface

 CONTAINS
    function constructor(arr_size) result(this)
        type(Test) :: this
        integer, intent(in) :: arr_size
        write(*,*) 'Constructor works'
        allocate(this % arr(arr_size))
    end function

    subroutine destructor(this)
        type(Test) :: this
        write(*,*) 'Destructor works'
        if (ALLOCATED(this % arr)) deallocate(this % arr)
    end subroutine        
end module

program test_client
    use test_class_module

    type(Test) :: tst
    tst = Test(100)
end
问题: 我用
valgrind
运行它,它打印了:

Constructor works
Destructor works
Destructor works
==22229== HEAP SUMMARY:
==22229== in use at exit: 432 bytes in 2 blocks
==22229== total heap usage: 10 allocs, 8 frees, 13,495 bytes allocated

问题:为什么仍然分配内存?(顺便说一句,我理解正确使用类需要赋值运算符,但这还不足以回答这个问题)谢谢你的建议。

实际上,在程序结束时不应该为

tst
调用析构函数。根据最新标准,主要程序变量为隐式
save
d。因此,在赋值中被覆盖时,它应该只为rhs上的函数结果和tst调用
析构函数。
如果将测试程序中的三行代码包装在
块中,您将看到所需的行为。我只修改了你的主程序:

program test_client
    use test_class_module
    write(*,*) '1 program start'
    BLOCK
        type(Test) :: tst
        write(*,*) '2 calling constructor'
        tst = Test(100)
        write(*,*) '3 block ending'
    END BLOCK
    write(*,*) '4 program end'
end
这将产生:

valgrind bin/SimpleTest
==10031== Memcheck, a memory error detector
...
1 program start
2 calling constructor
Constructor works
3 block ending
Destructor works
4 program end
==10031== 
==10031== HEAP SUMMARY:
==10031==     in use at exit: 0 bytes in 0 blocks
==10031==   total heap usage: 22 allocs, 22 frees, 12,417 bytes allocated
==10031== 
==10031== All heap blocks were freed -- no leaks are possible
==10031== 
==10031== For counts of detected and suppressed errors, rerun with: -v
==10031== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

save
属性是否仅在
end
处阻止终结,而不是在
tst
作为内部分配的lhs终结的情况下?那么,应该会产生两个最终结果?是的,关键是最后没有最终确定,并且阵列仍然是分配的。相似的:啊,是的,我现在明白你的意思了
tst
只定稿一次,但关键是不能在最后定稿。[我被“析构函数不应该为
tst
”所迷惑]因此,答案是:“析构函数工作良好,但不适用于主程序。在这种情况下,内存泄漏是可以的。”是吗?确切地说,对于主程序中定义的变量和模块变量,您必须自己调用终结器。