假设我有一个包含许多大数组的对象
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 MyObjectas 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_array1If 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.
更多推荐
发布评论