返回数组策略比较
在 Fortran 中,我可以使用三种方法从子例程返回数组。第一个是通过 intent(out)
参数。第二个是通过将数组作为结果的函数。第三个是拥有一个函数,其结果
是一个指向数组的指针,该指针在函数中分配。
每种方法的优点和缺点是什么?
In Fortran, I can return arrays from a subroutine with three approaches. The first one is via an intent(out)
parameter. The second one is via a function having the array as result
. The third one is to have a function having as result
a pointer to array, which is allocated in the function.
What are the advantages and disadvantages of each approach ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的做法是,当函数仅更改一个变量并且不产生其他输出时,使用函数返回。如果多个变量发生更改或过程执行其他操作,我会将输出变量放在参数列表中。这是一个风格的选择。使用指针可能会造成内存泄漏,尤其是作为函数参数返回的指针,因此我会避免使用此选项,除非在特定情况下有令人信服的原因。
更新:意图(输出)数组参数没有问题...不需要对数组的大小进行假设,如以下示例所示:
My practice is to use a function return when the function alters only one variable and makes no other output. If multiple variables are changed or the procedure performs other actions I would place the output variables in the argument list. This is a style choice. It is possible to create memory leaks with pointers, especially with pointers returned as function arguments, so I would avoid this option unless there was a compelling reason in the particular case.
UPDATE: There is no problem with an intent (out) array argument ... no assumptions need be made about the size of the array, as the following example shows:
然后您的函数可以是:
您可以愉快地传递这些 myvector 类型。只要记住在使用完数组后释放它们......
Then your function can be:
And you can pass these myvector types around happily. Just remember to deallocate the arrays when you're done with them...