This attribute would be much alike the ALLOCATABLE one, except that arrays declared with REALLOCATABLE could be resized dynamically by keeping the existing data in the array.
real, reallocatable :: a(:)
allocate(a(70))
a(:) = 1.0
reallocate(a(100)) ! a(1:70) is still 1.0
Why a reallocate
function wouldn’t do with a classical allocatable
array? Well, it could. But at low level there’s nothing like a reallocation: increasing the size of an array means 1) allocating a larger array, 2) copying the data from the old to the new array, 3) deallocating the old array while pointing to the new instead (this third step is handled by move_alloc
)
reallocatable
would instruct the compiler that reallocations will potentially occur, so that it can for instance overprovision the size under the hood. For instance with allocate(a(70))
the compiler would reserve 128*4 bytes, so that a further reallocate(a(100))
would not require any new allocation. Still, size(a)
before the reallocation would return 70
.
Of course, for reallocate(a(150))
the compiler would have to make a new allocation under the hood… But it would then reserve 256*4 bytes to prepare possible further reallocations.
Reallocatable arrays would also have an append routine:
call append(a,b)
, where b
would be scalar or an array. The result would be the same as a = [a, b]
, but without new allocation needed most of time.
This could work also with ranks > 1, but with some restrictions: only the last dimension could be resized:
real, reallocatable :: a(:,:)
allocate( a(70,40) )
reallocate( a(:,50) ) ! the new shape would be (70,50)
All of this is actually similar to how C++ vectors are implemented, I think.