Skip to content

set_allocate as a safe wrapper around ALLOCATE #395

Open
@Beliavsky

Description

@Beliavsky

I don't like to use allocation on assignment, because it is too inconspicuous, and for me, error-prone. I prefer it to be "glance clear" when I am allocating memory. A problem with using ALLOCATE, however, is that you must check if the variable is already ALLOCATEd. Should stdlib have a subroutine set_allocate that is safe to use for already ALLOCATEd variables? Below is an example for a 1D integer array. In my own codes I have overloaded set_allocate to handle 1D, 2D, and 3D arrays of the basic types, and I use set_allocate extensively. Using fypp, I think code for set_allocate could be generated for all types and ranks up to say 7. You could write set_allocate to have two optional arguments, source and mold, that would have to be the same shape if both present.

module m
implicit none
private
public :: set_allocate
contains
subroutine set_allocate(out,source)
! allocate out and set it to source
integer, intent(in)               :: source(:)
integer, intent(out), allocatable :: out(:)
allocate (out,source=source) ! intent(out) argument already deallocated
end subroutine set_allocate
end module m

program main
use m, only: set_allocate
implicit none
integer, allocatable :: ivec(:)
allocate (ivec(3))
! allocate (ivec,source=[5,2]) ! not legal since ivec already allocated
call set_allocate(ivec,source=[5,2]) ! legal
print*,"ivec=",ivec
end program main

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: utilitiescontainers, strings, files, OS/environment integration, unit testing, assertions, logging, ...

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions