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 for array elements ?

sugimoto605
Beginner
706 Views
If we allocate an array for a class with destructor(final procedure), the final procedure does not invoked for deallocate. Is there any method to invoke destructor ?

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

program MyApplication
use m_test
type(t_test),pointer::single_ptr
type(t_test),allocatable::single_alloc
type(t_test),allocatable::array_alloc(:)
type(t_test),pointer::pointer_alloc(:)
!--
write (*,*) "Single pointer works as expeted"
allocate(single_ptr)
deallocate(single_ptr)
!--
write (*,*) "Single allocatable works as expeted"
allocate(single_alloc)
deallocate(single_alloc)
!--
write (*,*) "Array allocatable does not invoke Dispose()"
allocate(array_alloc(1:1))
deallocate(array_alloc)
! deallocate(array_alloc(1:1))
!--
write (*,*) "Array-pointer does not invoke Dispose()"
allocate(pointer_alloc(1:1))
deallocate(pointer_alloc)
end program MyApplication

---Result---
Single pointer works as expeted
destructor
Single allocatable works as expeted
destructor
Array allocatable does not invoke Dispose()
Array-pointer does not invoke Dispose()

The result does not depend on array size (1:1 or 1:3 ...)
0 Kudos
1 Solution
IanH
Honored Contributor III
706 Views
The selection of the final procedure is based off the rank of the thing being finalized, just like the selection of generic procedures (except final procedures only ever have one argument).

If you wanted your procedure to be called when finalizing any array you could make it elemental. Alternatively provide a final procedure that takes a rank one array.

View solution in original post

0 Kudos
2 Replies
IanH
Honored Contributor III
707 Views
The selection of the final procedure is based off the rank of the thing being finalized, just like the selection of generic procedures (except final procedures only ever have one argument).

If you wanted your procedure to be called when finalizing any array you could make it elemental. Alternatively provide a final procedure that takes a rank one array.
0 Kudos
sugimoto605
Beginner
706 Views
Thanks! The following module works fine:
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
0 Kudos
Reply