Quantcast
Channel: Intel® Fortran Compiler
Viewing all articles
Browse latest Browse all 3270

Allocatable array in the derived type

$
0
0

Hello,

Suppose I have the following class:

interface my_type
    module procedure :: ctor
end interface

type :: my_type
    byte, allocatable :: buff(:)
contains
    final :: dtor
    procedure :: putData
    ...
end type

subroutine dtor(this)
    type(my_type) :: this
    if (allocated(this.buff)) deallocate(this.buff)
end subroutine

function ctor() result(this)
    type(my_type) :: this
    allocate(this.buff(100))
    ! Fill buff with some initial data ...
end function

The subroutine putData puts data into buff (its size will grow if need be, I use move_alloc), but at the very beginning some initial data should be put into it. The main code: 

type(my_type) :: a
a = my_type()
call a.putData(...)

It seems that using constructor in this way is not a good idea, because on assignment a = my_type() a copy of the allocated buffer is created and the original buffer (created in ctor) is destroyed. I see two immediate solutions: 1) introduce the special subroutine for initialization, 2) perform initialization on the first call to putData (using e.g. the logical flag isInitialized). Both seem somewhat deficient: the first one introduces additional subroutine that one should not forget to call after ctor, and the second one complicates the code for I have many putData's for different data types (it is a generic name).

Is it possible to devise something better? Thanks.


Viewing all articles
Browse latest Browse all 3270

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>