Intrinsic Subroutine (Generic): Moves an allocation from one allocatable object to another. Intrinsic subroutines cannot be passed as actual arguments.
CALL MOVE_ALLOC (from,to)
from |
(Input; output) Can be of any type and rank; it must be allocatable. |
to |
(Output) Must have the same type and kind parameters as from and have the same rank; it must be allocatable. |
If to is currently allocated, it is deallocated. If from is allocated, to becomes allocated with the same type, type parameters, array bounds, and value as from. Lastly, from is deallocated.
If to has the TARGET attribute, any pointer associated with from at the time of the call to MOVE_ALLOC becomes correspondingly associated with to. If to does not have the TARGET attribute, the pointer association status of any pointer associated with from on entry becomes undefined.
During implementation of MOVE_ALLOC, the internal descriptor contents are copied from from to to, so that the storage pointed to is the same.
Typically, MOVE_ALLOC is used to provide an efficient way to reallocate a variable to a larger size without copying the data twice.
The following shows an example of how to increase the allocated size of A and keep the old values with only one copy of the old values.
integer,allocatable::a(:),b(:)
n=2
allocate (a(n), b(n*2))
a=(/(i,i=1,n)/)
b=-1
print *, ' Old a = ',a
print *, ' Old b = ',b
print *, ' Allocated(a), allocated(b) = ', allocated(a), allocated(b)
b(1:n)=a ! Copy all of a into low end of b (the only copy)
print *, ' New b = ',b
call move_alloc(b,a) ! Make a the container, deallocate b (NO copy!)
print *, ' New a = ',a
print *, ' Allocated(a), allocated(b) = ', allocated(a), allocated(b)
end
The following shows another example:
! This program uses MOVE_ALLOC to make an allocated array X bigger and
! keep the old values of X by only making one copy of the old values of X
integer :: n = 2
real, allocatable :: x(:), y(:)
allocate (x(n), y(2*n)) ! Y is bigger than X
x = (/(i,i=1,n)/) ! put "old values" into X
Y = -1 ! put different "old values" into Y
print *, ' allocated of X is ', allocated (X)
print *, ' allocated of Y is ', allocated (Y)
print *, ' old X is ', X
print *, ' old Y is ', Y
y (1:n) = x ! copy all of X into the first locations of Y
! this is the only copying of values required
print *, ' new Y is ', y
call move_alloc (y, x) ! X is now twice a big as it was, Y is
! deallocated, the values were not copied
print *, ' allocated of X is ', allocated (X)
print *, ' allocated of Y is ', allocated (Y)
print *, ' new X is ', x
end
The following shows the output for the above example:
allocated of X is T
allocated of Y is T
old X is 1.000000 2.000000
old Y is -1.000000 -1.000000 -1.000000 -1.000000
new Y is 1.000000 2.000000 -1.000000 -1.000000
allocated of X is T
allocated of Y is F
new X is 1.000000 2.000000 -1.000000 -1.000000