ALLOCATABLE 数组还是 POINTER 数组? [英] ALLOCATABLE arrays or POINTER arrays?

查看:33
本文介绍了ALLOCATABLE 数组还是 POINTER 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Fortran 编写新代码,但在使用可分配数组或指针数组之间犹豫不决.我在某处读到可分配数组比指针数组有显着优势:

I am writing a new code in Fortran and hesitating between using allocatable arrays or pointer arrays. I read somewhere that allocatable arrays have significant advantages over pointer arrays:

1) 效率更高,因为它们在内存中总是连续的

1) More efficient because they are always contiguous in memory

2) 不可能出现内存泄漏

2) No memory leaks are possible

有人可以确认吗?您建议使用哪一种?这两种方案在代码执行速度方面的结果如何?

Can someone confirm this? Which one would you advise to use? What are the results in term of execution speed of the code between these two alternatives?

推荐答案

可分配数组可以产生更高效的代码,因为数组将是连续的.特别是如果数组传递给子例程,连续可以防止编译器创建临时副本的需要.

Allocatable arrays can result in more efficient code because the arrays will be contiguous. Particularly if the array is passed to a subroutine, being contiguous can prevent the need for the compiler creating a temporary copy.

对于子例程中的局部变量(没有 SAVE 属性)(对于 Fortran 95 及更高版本),可分配数组在子例程退出时自动释放,避免内存泄漏.allocatables 不可能发生内存泄漏,除非程序员不释放不再需要的数组.

For local variables in subroutines (without the SAVE attribute) (for Fortran 95 and higher), allocatable arrays are automatically deallocated upon exit from the subroutine, avoiding a memory leak. Memory leaks aren't possible with allocatables, except in the sense of the programmer not deallocating an array that is no longer need.

使用指针,您可以重新分配指针,从而导致一些内存无法访问和丢失——泄漏的一种形式.如果可分配对象可以完成这项工作,我建议使用该方法而不是指针.

With pointers, you can reassign a pointer, leaving some memory inaccessible and lost -- one form of a leak. If an allocatable will do the job, I recommend using that method instead of a pointer.

使用指针的一些原因:获取数组的一部分,或创建数据结构,例如链表.为了创建在运行时确定大小的数组,我将使用可分配的.

Some reasons to use pointers: taking a section of an array, or creating a data structure such as a linked list. For the purpose of creating an array of size determined at run time, I'd use an allocatable.

这篇关于ALLOCATABLE 数组还是 POINTER 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆