I have a program with a derived type that has a final procedure and an assignment operator overload, as shown below:
module MyTypeModule implicit none type MyType real, allocatable, dimension(:) :: myArray contains final :: Finalize end type MyType interface assignment(=) module procedure :: MyTypeAssign end interface contains subroutine Finalize(this) type(MyType), intent(inout) :: this if (allocated(this%myArray)) deallocate(this%myArray) end subroutine Finalize subroutine MyTypeAssign(left,right) type(MyType), intent(out) :: left type(MyType), intent(in) :: right if (allocated(right%myArray)) left%myArray = right%myArray end subroutine MyTypeAssign end module MyTypeModule program TestCodeAssignmentFinalize use MyTypeModule implicit none type(MyType) :: a,b allocate(a%myArray(10)) a%myArray = 1.0 write(*,*) "a is allocated? ",allocated(a%myArray) write(*,*) "setting a = a" a = a write(*,*) "a is allocated? ",allocated(a%myArray) write(*,*) "b is allocated? ",allocated(b%myArray) write(*,*) "setting b = a" b = a write(*,*) "b is allocated? ",allocated(b%myArray) end program TestCodeAssignmentFinalize
The console output is as follows:
a is allocated? T setting a = a a is allocated? T b is allocated? F setting b = a b is allocated? T
When I comment out the assignment interface, I get the following console output:
a is allocated? T setting a = a a is allocated? F b is allocated? F setting b = a b is allocated? F
You can see that with intrinsic assignment, the array in a is getting deallocated before being assigned to itself, whereas it remains allocated with the overloaded assignment. Is this expected behavior? If it is expected, then is there a way to get around the deallocation when I have a = a and intrinsic assignment?