two questions on allocatable member fields

Sylwester Arabas sarabas@igf.fuw.edu.pl
Tue Mar 5 23:35:00 GMT 2013


Dear All,

Sorry for asking perhaps too RTFM-ish questions here...:

Are (according to the standard, and in practice in gfortran) allocated 
allocatable member fields deallocated automatically when an instance of 
a type goes out of scope?

For example, with the code below:

------------------------------------------------------------
module m
   implicit none

   type :: t
     real, allocatable :: r(:)
     contains
     procedure :: init => init
   end type

   contains

   subroutine init(this)
     class(t) :: this
     allocate(this%r(1024))
   end subroutine
end module

program test
   use m
   implicit none
   block
     type(t) :: i
     call i%init()
   end block
end
------------------------------------------------------------

would i%r be deallocated at the last "end block", or is it necessary to 
call deallocate() explicitly through some destructor-like method?


And a related question: an allocatable member of a type cannot be 
declared as a target. How to point a pointer to an allocatable member of 
a type?

For example (extension of the code above):
------------------------------------------------------------
module m
   implicit none

   type :: t
     real, allocatable :: r(:) ! cannot be a target
     contains
     procedure :: init => init
     procedure, nopass :: prnt => prnt
   end type

   contains

   subroutine init(this)
     class(t) :: this
     real, pointer :: p(:)

     allocate(this%r(1024))
     p => this%r(1:10)
     call prnt(p)
   end subroutine

   subroutine prnt(ptr)
     real, pointer :: ptr(:)
     print*, ptr
   end subroutine
end module
------------------------------------------------------------

gives:

------------------------------------------------------------
     p => this%r(1:10)
          1
Error: Pointer assignment target is neither TARGET nor POINTER at (1)
------------------------------------------------------------

but making t%r a target is impossible:

------------------------------------------------------------
     real, allocatable, target :: r(:) ! cannot be a target
                              1
Error: Attribute at (1) is not allowed in a TYPE definition
------------------------------------------------------------

Is there any way around it?

Thanks for help,
Sylwester

-- 
http://www.igf.fuw.edu.pl/~slayoo/



More information about the Fortran mailing list