简体   繁体   中英

Pointer or allocatable for type components

Say you have a declared type dat1 which has a default numbers of members. Depending on run time, this dat1 may or may not be extended with other types. This is easy as you can use the extends feature. However, if you have an array of dat1 and some elements of that array may or may not want to inherit another type - how is this done most reasonably.

I have the following example:

type dat1 

  real :: x(3)
  type(dat2), allocatable :: rnd 
  type(dat1), pointer :: next => dat1
end dat1

Now I used a linked list to do this. My question is basically if it is the correct way to declare the second type rnd as an allocatable, and then just allocate it whenever a node requests it. The other option is to declare it as a pointer ie type(dat2), allocatable :: rnd , now is there any significant differences, despite the common Fortran differences with pointers vs alloctables like explicit/implicit deallocation, contiguous memory etc.

Note that no matter what, each dat1 node will always have either 0 or 1 rnd type attached to it.
I was considering during runtime that I would check if rnd was allocated or for pointer it would be associated.

Components of a derived type have the same concerns as general pointer/allocatable variables .

However, there are additional aspects of interest regarding components:

  • automatic deallocation : on deallocating a derived type object any allocated allocatable components are deallocated; pointer components are not automatically deallocated or disassociated.

  • type references : both pointer and allocatable components may be of the type being defined (here dat1 ) or defined at a later point, but for allocatable components this is a feature not available before Fortran 2008 and is not massively supported by compilers.

One difference not mentioned in the linked question's answer is relevant to this question. Here you say:

I was considering during runtime that I would check if rnd was allocated or for pointer it would be associated

It is always allowed to ask ALLOCATED(x%rnd) (allocatable), but it is not always allowed to ask ASSOCIATED(x%rnd) (pointer). A pointer component may be of undefined association status whereas an allocatable component will always have defined allocation status. 1

You may therefore want to set an initial association status of the pointer component.


1 The case of undefined allocation status (of Fortran 90) and allocatable components have never co-existed in the standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM