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

时间:2014-09-18 08:06:13

标签: 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 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

问题:为什么还要分配内存? (P.S.我理解需要使用赋值运算符来正确使用类,但这个问题还不够)感谢任何想法。

2 个答案:

答案 0 :(得分:2)

实际上,在程序结束时不应该为tst调用析构函数。根据最新标准,主要程序变量隐含save d。因此,它只应在rhs上为函数结果调用destructor,在赋值时覆盖tst

答案 1 :(得分:0)

为后人。 如果您在测试程序中将三行包裹在<!DOCTYPE html> <html lang="en" ng-app="myContent"> <head> <meta charset="UTF-8"> <title>ShopME Tops</title> <link rel="stylesheet" type="text/css" href="mystyle.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font- awesome/4.7.0/css/font-awesome.min.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script type="text/javascript" src="myscript.js"></script> </head> <body> <div ng-controller="ContentController" class="container"> <div class="row"> <div> {{ imageCount }}</div> </div> </div> </body> </html>中,您会看到所需的行为。我只修改了你的主程序:

BLOCK

这会产生:

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