2

기초 : 나는 생성자와 소멸자를 사용하여 Fortran에서 좋은 코드를 작성하려고합니다. 여기 은 매우 간단 Test 클래스의 예이며 클라이언트의 :Fortran에서 소멸자로 메모리 할당 해제

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 

질문 : 메모리는 여전히 이유 할당? (추신 : 나는 적절한 클래스 사용을 위해 할당 연산자의 필요성을 이해하지만이 질문에는 충분하지 않다.) 어떤 아이디어라도 가져 주셔서 감사합니다.

답변

2

실제로 소멸자는 프로그램 끝에서 tst에 대해 호출하면 안됩니다. 최신 표준에 따르면 주 프로그램 변수는 암시 적으로 save d입니다. 따라서 할당에서 덮어 쓰기되는 경우 tst에 대해서만 rhs의 함수 결과에 대해 destructor을 호출해야합니다.

+0

을하지 않는'save' 오히려 tst'과 같이 확정되는 '경우보다 만 end''에서 마무리를 방지 속성합니까 본질적 과제를위한 lhs? 따라서 두 가지 결론이 내려져야합니다. – francescalus

+0

예, 끝에서 최종화되지 않았고 배열이 할당 된 채로 남아있었습니다. 유사 : https://software.intel.com/en-us/forums/topic/271088 –

+0

아, 지금 당신의 요지를 이해합니다. 'tst'는 한 번 마무리되었지만 마지막에는 결정적인 것이 아닙니다. [소멸자가'tst'를 요구해서는 안됩니다.] – francescalus

0

후손을 위해. 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 

이 생산 : 난 단지 당신의 메인 프로그램 수정

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)