2012-04-20 62 views
0

我有一個Fortran模塊,我希望儘可能地遵循OOP哲學,同時仍然使它與Fortran 2003兼容。此模塊基本上:(a)分配/釋放臨時數組緩衝區,並且(b)提供一個函數do_F,它對一些數據進行操作。該函數do_F使用這些臨時緩衝區,但也取決於幾種輔助類型。OOP Fortran:保存指向變量(IN)的指針

我很清楚,我應該把緩衝區放到一個類型中,並在適當的時候初始化/釋放。但是,由於每次調用do_F需要多個參數,我相信什麼纔是最好的設計策略。

更具體的,請考慮以下實現:

  1. 每do_F被稱爲

    type object_t 
        ! lots of private buffers 
        real, allocatable :: buf1(:,:,:), buf2(:,:,:), etc. 
    end type object_t 
    
    subroutine init_object(this) 
        type(object_t), intent(INOUT) :: this 
    
        allocate(this%buf1(..., ..., ...)) 
        !... 
    end subroutine init_object 
    
    subroutine do_F(this, data, aux1, aux2, ..., auxN) 
        type(object_t), intent(INOUT) :: this 
        type(data_t), intent(INOUT) :: data 
        type(aux1_t), intent(IN) :: aux1 
        !... 
    
        !do stuff on data using the buffers and values stored 
        ! in aux1 .. auxN 
    end subroutine do_F 
    
  2. 保存指針到do_F需要

    類型時通過大量的類型
    type object_t 
        ! lots of private buffers 
        real, allocatable :: buf1(:,:,:), buf2(:,:,:), etc. 
    
        ! pointers to auxiliary types 
        type(aux1_t), pointer :: aux1_ptr 
        !... 
    end type object_t 
    
    subroutine init_object(this, aux1, aux2, ..., auxN) 
        type(object_t), intent(INOUT) :: this 
        type(aux1_t), intent(IN), target :: aux1 
        !... 
    
        allocate(this%buf1(..., ..., ...)) 
        !... 
    
        this%aux1_ptr => aux1 
        !... 
    end subroutine init_object 
    
    subroutine do_F(this, data) 
        type(object_t), intent(INOUT) :: this 
        type(data_t), intent(INOUT) :: data 
    
        !do stuff on data using the buffers and values stored 
        ! in this%aux1_ptr .. this%auxN_ptr 
    end subroutine do_F 
    

我的具體問題是:

  1. 是執行#2是否有效? PGI編譯器並沒有抱怨,但我聽說函數返回後,意圖(IN)不再明確定義
  2. 使用此方案的指針會出現性能損失嗎?即使我不寫入這些aux_ptr,編譯器是否能夠優化我的代碼以及#1的情況?

一些注意事項:

  1. 功能do_F被稱爲〜100次,每次調用需要幾分鐘,對大型陣列進行操作。
  2. 除了do_F,還有do_G和do_H函數對相同的數據進行操作並使用相同的輔助變量。這就是爲什麼我想減少傳遞給函數的變量數量的原因。
  3. 我不想將所有的輔助變量合併到一個類型中,因爲它們在大型HPC代碼的其餘部分中使用。

謝謝!

回答

2

意圖IN變量在返回後定義良好,如果它們在調用之前。該程序不允許改變它們。指針變量的值例外,您可以在其中更改目標的值,但不會指向intent(IN)指針僞參數的指針的關聯狀態。

雖然我不確定效率。快速閱讀後,版本2看起來更好。

+0

感謝downvoter。我實際上正在尋找相當長的一段時間來修復它,但我找不到它。並感謝伊恩指出真實的狀態。 – 2015-11-23 18:04:50