本文介绍了Fortran动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要这样的东西:



我想创建一个返回数据的子例程作为指针:

 子程序f(p)
类型(tra),指针p
类型(tra),目标::实例

p = >实例
do_work(实例)
结束子程序

严格地说我想以实现c ++new运算符的模拟。



然后,我想要使用如下子例程:

<$ (p)
调用f(p2)
结束(tra),指针:: p1,p2
调用f(p1)
结束子程序

上面的代码可能不起作用,因为我认为f中的instance会在f ,然后下一次f的调用再次在内存中的同一个地方创建instance。

特别是我发现 p1 p2 指向相同的对象,但我想这是依赖于编译器的。 是真的



我认为可能的解决方案是:

 子程序f(p)
类型(tra),指针p
类型(tra),allocatable,target :: instance(:)

p => instance(1)
do_work(instance(1))
end subroutine


解决方案

它是 ALLOCATE 。你试图做的事情应该是这样的:

 子程序f(p)
类型(tra),指针:: p

!你可以用这种方式实际泄漏记忆!需要小心。
if(associated(p))then
stop可能的内存泄漏 - p是关联的
end
allocate(p)
do_work(p)
结束子程序



不,这是不正确的。本地子程序变量通常分配一次(甚至只初始化一次),参见例如。 Fortran 90规范,第14章,尤其是第14.7节。

I am trying to create a subroutine that returns data as a pointer:

I want something like that:

subroutine f(p)
     type(tra), pointer p
     type(tra), target :: instance

     p=>instance
     do_work(instance)
end subroutine

Strictly speaking I want to implement analogue of c++ "new" operator.

I want then to use such a subroutine as follows:

subroutine other
    type(tra), pointer :: p1,p2
    call f(p1)
    call f(p2)
end subroutine

The above code may not work, as I suppose "instance" inside f is destroyed after f quits, and the next call of f creates "instance" again in the same place in memory.

In particular I find with p1 and p2 pointing to the same objects, but I guess this is compiler-dependent. Is it true?

I think that a possible solution is:

subroutine f(p)
     type(tra), pointer p
     type(tra), allocatable, target :: instance(:)

     p=>instance(1)
     do_work(instance(1))
end subroutine

Is this the "official" way of doing things?

解决方案

It is ALLOCATE. The thing you are trying to do should be simply this:

subroutine f(p)
     type(tra), pointer :: p

     ! you can actually leak memory this way! caution required.
     if(associated(p)) then
         stop "possible memory leak - p was associated"
     end
     allocate(p)
     do_work(p)
end subroutine

No, this is not true. Local subroutine variables are usually "allocated" once (and even initialized only once), see e.g. Fortran 90 spec, chapter 14, especially section 14.7.

这篇关于Fortran动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 23:03