finalise_array Module Subroutine

recursive module subroutine finalise_array(this)

Finalise array - clean up memory safely

Arguments

Type IntentOptional Attributes Name
type(array_type), intent(inout) :: this

Source Code

  recursive module subroutine finalise_array(this)
    !! Finalise array - clean up memory safely
    implicit none
    type(array_type), intent(inout) :: this

    ! write(*,*) "finalising array loc: ", loc(this), this%is_temporary, this%operation

    ! First deallocate owned pointers (operands and gradient) to prevent leaks
    if(.not.this%is_temporary)then
       if(associated(this%left_operand))then
          if(this%owns_left_operand)then
             !call this%left_operand%deallocate()
             deallocate(this%left_operand)
          end if
          nullify(this%left_operand)
       end if

       if(associated(this%right_operand))then
          if(this%owns_right_operand)then
             !call this%right_operand%deallocate()
             deallocate(this%right_operand)
          end if
          nullify(this%right_operand)
       end if

       if(associated(this%grad))then
          if(this%owns_gradient)then
             !call this%grad%deallocate()
             deallocate(this%grad)
          end if
          nullify(this%grad)
       end if
    end if

    ! Deallocate all allocatable arrays
    call this%deallocate()

    ! Reset ownership flags and nullify procedure pointers
    this%owns_gradient = .false.
    this%owns_left_operand = .false.
    this%owns_right_operand = .false.
    nullify(this%get_partial_left)
    nullify(this%get_partial_right)
    nullify(this%get_partial_left_val)
    nullify(this%get_partial_right_val)
    nullify(this%get_partial_left_val_sum)
    nullify(this%get_partial_right_val_sum)
    this%is_temporary = .true.
    ! write(*,*) "finalised array loc: ", loc(this)

  end subroutine finalise_array