带有指针的 Fortran 函数导致正常赋值 [英] Fortran Functions with a pointer result in a normal assignment

查看:19
本文介绍了带有指针的 Fortran 函数导致正常赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对此处找到的问题进行了一些讨论后 在 Fortran 中正确执行 Final 例程我认为了解具有指针结果的函数何时适合与普通或指针赋值一起使用会很有用.例如,给定这个简单的函数

After some discussion on the question found here Correct execution of Final routine in Fortran I thought it will be useful to know when a function with a pointer result is appropriate to use with a normal or a pointer assignment. For example, given this simple function

 function pointer_result(this)
 implicit none 
 type(test_type),intent(in) pointer :: this 
 type(test_type), pointer :: pointer_result 

 allocate(pointer_result)
 end function 

我通常会执行 test=>pointer_result(test),其中 test 已用 pointer 属性声明.虽然正常的赋值 test=pointer_result(test) 是合法的,但它意味着不同的东西.

I would normally do test=>pointer_result(test), where test has been declared with the pointer attribute. While the normal assignment test=pointer_result(test) is legal it means something different.

与指针赋值相比,普通赋值意味着什么?

What does the normal assignment imply compared to the pointer assignment?

什么时候使用一个或另一个分配有意义?

When does it make sense to use one or the other assignment?

推荐答案

正常作业

test = pointer_result()

表示 test 的当前目标的值将被结果指针所指向的值覆盖.如果 test 指向某个无效地址(未定义或为空),程序将崩溃或产生未定义的结果.函数分配的匿名目标将不再有指向它的指针,内存将被泄露.

means that the value of the current target of test will be overwritten by the value pointed to by the resulting pointer. If test points to some invalid address (is undefined or null) the program will crash or produce undefined results. The anonymous target allocated by the function will have no pointer to it any more and the memory will be leaked.

这几乎没有任何合法用途,但是当一个人打错字并写成 = 而不是 => 时,很可能会发生这种情况.它制作起来非常简单,并且一些样式指南建议不要使用指针函数.

There is hardly any legitimate use for this, but it is likely to happen when one makes a typo and writes = instead of =>. It is a very easy one to make and several style guides recommend to never use pointer functions.

这篇关于带有指针的 Fortran 函数导致正常赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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