【发布时间】:2020-02-09 02:12:41
【问题描述】:
我正在尝试将目标复制到派生类型变量中的指针到另一个相同类型的变量,但我不知道该怎么做
假设我有一个分散的点列表,我想对其进行三角测量。我会有一个
type :: triangulation
type(vertex), allocatable :: points(:)
type(triangle), allocatable :: triangles(:)
end type triangulation
为了节省内存,我使用指向节点的指针来定义每个三角形:
type :: triangle
type(vertex), pointer :: A => null()
type(vertex), pointer :: B => null()
type(vertex), pointer :: C => null()
end type triangle
这将在同一个对象中。例如,要在三角剖分中生成一个新三角形,我将运行:
type(triangle) function triangulation_new_triangle(this,iA,iB,iC) result(tri)
class(triangulation), intent(in), target :: this
integer, intent(in) :: iA, iB, iC ! Indices of the three nodes
tri%A => this%points(iA)
tri%B => this%points(iB)
tri%C => this%points(iC)
end function
现在,假设我必须重新分配三角形列表。如何将其复制到相同三角剖分的新列表中,而不会丢失其指针引用?即,我想做这样的事情:
subroutine triangulation_reallocate(this)
class(triangulation), intent(inout) :: this
! Local variables
integer, parameter :: TRIANGLE_CHUNK_SIZE = 1024
integer :: old_size
type(triangle), allocatable :: new_triangle_pool(:)
! Get old size
old_size = merge(size(this%triangles),0,allocated(this%triangles))
! Allocate new array of triangles
allocate(new_triangle_pool(old_size+TRIANGLE_CHUNK_SIZE))
! Copy data from old to new array
[..... missing code here .......]
! Move allocation back to the triangulation object
call move_alloc(from=new_triangle_pool,to=this%triangles)
end subroutine triangulation_reallocate
我正在考虑一种复制三角形关联的方法。如果我这样做:
do i=1,old_size
new_triangle_pool(i) = this%triangles(i)
end do
这行得通吗?我担心如果我复制以下内容:
new_triangle_pool(i)%A => this%triangles(i)%A
那么这是一个指向指针而不是指向原始顶点的指针,当旧的this%triangles 变量被释放时关联会丢失?
【问题讨论】:
-
您是否关心
y=>z; x=>y的最终效果是否像x=>z? -
是的:我想要
x=>z,但是套路不知道z是什么;另外,中间的y将通过调用move_alloc被释放
标签: oop pointers fortran fortran2003