Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29253 Discussions

Final procedure does not work if the code contains deallocate statement never called

sugimoto605
Beginner
360 Views
In the following program, calling sub_ptr%new() should invoke final procedure disposes(), but it is not invoked if I comment out a deallocate statement in subroutine clear() in module m_test_sub.

module m_test
private
public::t_test
type::t_test
private
contains
final::dispose,disposes
end type t_test
contains
subroutine dispose(this)
type(t_test)::this
write (*,*) "destructor"
end subroutine dispose
subroutine disposes(this)
type(t_test)::this(:)
write (*,*) "destructor2"
end subroutine disposes
end module m_test

module m_test_sub
use m_test
private
public::t_test_sub
type::t_test_sub
type(t_test),pointer::ptrs(:) =>null()
contains
procedure::new
end type t_test_sub
contains
subroutine clear(this)
class(t_test_sub)::this
allocate(this%ptrs(0:5))
! deallocate(this%ptrs) ! <----------------------------- STRANGE STATEMENT HERE
end subroutine clear
subroutine new(this)
class(t_test_sub)::this
allocate(this%ptrs(0:5))
write (*,*) "Start test"
deallocate(this%ptrs)
write (*,*) "End of test"
end subroutine new
end module m_test_sub

program MyApplication
use m_test_sub
type(t_test_sub)::sub_ptr
call sub_ptr%new()
write (*,*) "---end---"
end program MyApplication

**** RESULT (with deallocate comment out) ****
Start test
destructor2
End of test
---end---
**** RESULT (with deallocate statement in CLEAR() ) ****
Start test
End of test
---end---

I dont understand why the result depends on the code which is never called.... Compiler version is 12.1(x86_64)

Also I found that subroutine new() comes eariler in m_test_sub, that is,
.....
end type t_test_sub
contains
subroutine new(this)
class(t_test_sub)::this
allocate(this%ptrs(0:5))
write (*,*) "Start test"
deallocate(this%ptrs)
write (*,*) "End of test"
end subroutine new
subroutine clear(this)
class(t_test_sub)::this
allocate(this%ptrs(0:5))
deallocate(this%ptrs) ! <----------------------------- STRANGE STATEMENT HERE
end subroutine clear
end module m_test_sub

The final procedure is invoked even if I include deallocate() statement in subroutine clear():

Start test
destructor2
End of test
---end---

So the result also depend on which comes eariler, clear() and new().

0 Kudos
0 Replies
Reply