在Fortran中使用'getter'函数时,内存中重复(Duplicates in memory when using 'getter' functions

编程入门 行业动态 更新时间:2024-10-26 18:15:41
在Fortran中使用'getter'函数时,内存中重复(Duplicates in memory when using 'getter' functions in Fortran)

假设我有一个包含许多大数组的对象

type, public :: MyObject implicit none real*8, allocatable, private :: array1, array2, ... etc contains procedure :: get_array1, get_array2, ... etc end type MyObject

以及'getter'功能

function get_array1(self) result(array1) implicit none class(MyObject), intent(in) :: self real, dimension(size(self%array1)) :: array1 array1 = self%array1 end function get_array1

如果我在程序中使用getter函数如下

somearray = MyObject%get_array1()

然后我将最终得到存储在MyObject和somearray中的array1的值,这是浪费的。 但是,如果我直接将get_array1的结果get_array1给另一个子例程:

call a_subroutine(arg1, arg2, MyObject%get_array1())

或者如果我直接在主程序中引用它而不将其分配给新数组:

a_sum = sum(a_vector(:)*MyObject%get_array1())

我最终会得到存储在内存中的array1的多个副本吗? 或者在子程序调用或求和后是否释放包含函数返回值的内存?

Let's say I have an object containing a number of large arrays

type, public :: MyObject implicit none real*8, allocatable, private :: array1, array2, ... etc contains procedure :: get_array1, get_array2, ... etc end type MyObject

as well as 'getter' functions

function get_array1(self) result(array1) implicit none class(MyObject), intent(in) :: self real, dimension(size(self%array1)) :: array1 array1 = self%array1 end function get_array1

If I use the getter function in a program as follows

somearray = MyObject%get_array1()

then I will end up with the values in array1 stored both in MyObject and in somearray, which is wasteful. If however I directly pass the result of get_array1 to another subroutine:

call a_subroutine(arg1, arg2, MyObject%get_array1())

or if I refer to it directly in the main program without assigning it to a new array:

a_sum = sum(a_vector(:)*MyObject%get_array1())

am I going to end up with multiples copies of array1 stored in memory? Or will the memory containing the function return value be freed after the subroutine call or the summation?

最满意答案

确实很可能会为数组产品创建一个临时的

a_sum = sum(a_vector(:)*MyObject%get_array1())

因为sum是内在的,所以soe编译器可能能够优化它,但总的来说可能是暂时的。

这些临时数据在呼叫站点创建并在呼叫后被销毁。 它们可以放在堆栈上或堆上,具体取决于编译器,它的设置和数组大小。

您不必担心在通话后阵列会存活太久。

It is indeed really likely that a temporary will be created for the array product in

a_sum = sum(a_vector(:)*MyObject%get_array1())

Because sum is intrisic, soe compilers may be able to optimize it, but in general a temporary is likely.

Such temporaries are created at the call site and destroyed after the call. They may be placed on the stack or on the heap depending on the compiler, its setttings and the array size.

You shouldn't worry that the array will live for too long after the call.

更多推荐

本文发布于:2023-07-18 03:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   内存   getter   Fortran   memory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!