私のプログラムでは、特定の派生型の配列を含むコンテナー型を作成したいと考えています。配列のすべてのコンポーネントでプロシージャを呼び出す、コンテナのタイプ バインド プロシージャを追加したいと考えています。配列のサイズはさまざまなので、自動再割り当て機能を使用してみました。割り当て可能な文字で問題が発生しました。
セットアップを示す小さなスニペットを次に示します。
module realloc_test
implicit none
type :: number_t
character(:), allocatable :: number_c ! this does not work
! character(len=10) :: number_c ! this works
integer :: number_i
end type number_t
type number_container
integer :: listsize
type(number_t), allocatable, dimension(:) :: all_numbers
contains
procedure add
end type number_container
contains
subroutine add (this, number_in)
class(number_container), intent(inout) :: this
type(number_t), intent(inout) :: number_in
if (.not. allocated(this%all_numbers)) then
allocate(this%all_numbers(1), source = number_in)
this%listsize = 1
else
! reallocate -> add entry
this%all_numbers = [ this%all_numbers, number_in ]
this%listsize = SIZE (this%all_numbers)
end if
end subroutine add
end module realloc_test
program testprog
use realloc_test
implicit none
integer :: i
type(number_t) :: one, two, three, four
type(number_container) :: number_list
one = number_t ('one', 1)
two = number_t ('two', 2)
three = number_t ('three', 3)
four = number_t ('four', 4)
call number_list%add(one)
call number_list%add(two)
call number_list%add(three)
call number_list%add(four)
do i = 1, number_list%listsize
print*, number_list%all_numbers(i)%number_c
print*, number_list%all_numbers(i)%number_i
end do
end program testprog
を使用して、ifortでコンパイルしました
-assume realloc_lhs
自動再割り当てを有効にします。出力は次のとおりです。
1
??n
2
3
four
4
最後のエントリは正しく表示されます。配列の古い部分をコピーすると、割り当て可能なコンポーネントで問題が発生するようです。固定文字長を使用する場合、問題は発生しません。自動再割り当てをそのように使用すると、正確にはどうなりますか? これをより安全に行うための他のオプションはありますか?