Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

"initial" statement / automatic constructor for a Fortran derived type

I am wondering if there is a constructor-like mechanism in Fortran for derived types, in such a way, that whenever an instance of a type is created, the constructor is called automatically. I read this question, but it was unsatisfactory to me.

Schematic example for completeness:

module mod
integer :: n=5

type array
    real, dimension(:), allocatable :: val
  contains
    procedure :: array()
end type 

subroutine array(this)
  allocate(this%val(n))
end subroutine

end module

Now when I create an instance of type(array) :: instance I'd like the constructor array(instance) to be called automatically without any extra call array(instance) in the code added manually.

I found some promising information on this site, but nowhere else: It specifies a constructor-like mechanism with the type-bound procedure declared initial,pass :: classname_ctor0. What standard is this? ifort in version 16 won't compile the example posted there and I have no standard available.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An 'initial' subroutine is not, unlike a final subroutine, part of a Fortran standard.

In a derived type certain components may have initial values, set by default initialization, such as

type t
  integer :: i=5
end type t
type(t) :: x  ! x%i has value 5 at this point

However, allocatable array components (along with some other things) may not have default initialization and always start life as unallocated. You will need to have a constructor or some other way of setting such an object up if you wish the component to become allocated.

In the case of the question, one thing to consider is the Fortran 2003+ parameterized type:

type t(n)
  integer, len :: n
  integer val(n)
end type
type(t(5)) :: x  ! x%val is an array of shape [5]

This naturally isn't the same this as an allocatable array component with an "initial" shape, but if you just want the component to be run-time initial customizable shape this could suffice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...