mac osx catalina (latest)
gfortran 9.2
fortran standard "gnu"
Through something like the code below, I came to understand that, at least in this case, that within the function get_number
the result
value is constructed, and then results are copied over to the receiving variable. Probably I've also done a no-no by having a pointer target a local variable inside that function, but perhaps the compiler was being nice to me by not deallocating a local variable so my pointer was still okay.
My question is, is this how all function calls behave, namely that the value, whether a simple type or a complex type, is constructed in memory, and then the values are copied over and the original result is thrown away? I was under the impression that the variable receiving the value of the function call was just given the memory of the constructed result.
Suppose I felt that lots of memory copying was wasteful, or suppose as in the code below that it breaks my code, and I wanted to avoid it when doing many many function calls. Is the solution to replace them with subroutine calls? But I like function calls. If memory copying is what happens normally, is there a way to avoid memory copying when doing function calls?
module nums
type number
real :: n
end type number
type number_parent
type(number), pointer :: p
contains
procedure, pass(this) :: get_number
end type number_parent
contains
function get_number(this) result(n)
class(number_parent) :: this
type(number), allocatable, target :: n
allocate(n)
n%n = 1.0
this%p => n
end function get_number
end module nums
program main
use nums
implicit none
type(number) :: n
type(number_parent) :: np
n = np%get_number()
print *, n%n
print *, np%p%n
n%n = n%n + 1.0
print *, n%n
print *, np%p%n
end program main
program output
> ./a.out
1.00000000
1.00000000
2.00000000
1.00000000