openfoam 智慧指標探索

TJUHE發表於2023-03-02

前言

今天看到一個程式,用到了智慧指標,

virtual tmp<volScalarField> rho() const;

藉此機會把有關智慧指標的知識體系重新梳理一遍


智慧指標autoPtr的由來:

首先要說明智慧指標本質上是模板類,是對原有指標的改進,相比更安全,
image

of對autoPtr的描述如下:

An auto-pointer similar to the STL auto_ptr but with automatic casting
to a reference to the type and with pointer allocation checking on access.

of中的智慧指標autoPtr很像原有的auto_ptr,但不是對原有的封裝,而是重新寫了一遍

再看std::auto_ptr
std::auto_ptr的定義大致如下:

template <typename _Tp>
class auto_ptr
{
private:
    _Tp *_M_ptr;

public:
    explicit auto_ptr(_Tp *__p = 0) throw();
    auto_ptr(auto_ptr &__a) throw();
    auto_ptr &operator=(auto_ptr &__a) throw();
    ~auto_ptr();

    _Tp &operator*() const throw();
    _Tp *operator->() const throw();

    _Tp *get() const throw();
    _Tp *release() throw();
    void reset(_Tp *__p = 0) throw();
};

再看我們of中的autoPtr是何其相似,

template<class T>
class autoPtr
{
        mutable T* ptr_;
public:
    typedef T Type;
        inline explicit autoPtr(T* = nullptr);
        inline autoPtr(const autoPtr<T>&);
        inline autoPtr(const autoPtr<T>&, const bool reuse);
        inline ~autoPtr();

            inline bool empty() const;
            inline bool valid() const;
            inline T* ptr();
            inline void set(T*);
            inline void reset(T* = nullptr);
            inline void clear();

            inline T& operator()();
            inline const T& operator()() const;
            inline T& operator*();
            inline const T& operator*() const;
            inline operator const T&() const;
            inline T* operator->();
            inline const T* operator->() const;
            inline void operator=(T*);
            inline void operator=(const autoPtr<T>&);
};

在autoPtr中,我們也能看到在autoPtr中加了很多unique_ptr的元素,比如說reset(),

那為什麼要用智慧指標呢,他的應用場景是哪些,下次我們自己寫的時候要什麼時候用


為什麼要用智慧指標:

舉個例子,比如說我們要實現插值演算法,用matlab寫,這很簡單

result = function(input)

現在我們學習C++了,知道了可以傳指標或引用,可以這樣寫

function(&result, input);

相比之下of更傾向於使用matlab的書寫方式
因為簡單
不僅是看起來簡單,寫起來也簡單,可以更直觀的表達想法
對於沒接觸過C或C++的人來說,不必瞭解引用左值右值等一系列知識
在of中寫動量方程,

fvVectorMatrix UEqn
(
	fvm::ddt(rho, U)
	+ fvm::div(rhoPhi, U)
	+ turbulence->divDevRhoReff(rho, U)
);

首先這是個類fvVectorMatrix的建構函式,還是個複製構造
那這就需要括號內運算子過載以及函式返回型別都是fvVectorMatrix類

對於需要引入方程的人來說顯式寫法更直觀更簡單,如果寫成function(&result, input)這樣,一個兩個還好,方程多了會非常亂

但是C++作為效率最高的語言,引用這個概念的提出肯定有他的道理
引用是什麼,很多說是別名
實際上引用的本質是指標常量,如果換C語言的寫法是這樣的

int* const rb = &a;

matlab以簡單易用著稱,但用過matlab的人都知道matlab的效率極低,
本科時候當時不會向量化程式設計,參加數學建模比賽跑一個迴圈,跑了整整24小時,筆記本散熱也不大行,後來送修主機板了
為什麼matlab效率低,很關鍵的一點是matlab一直都是複製複製
C/C++指標傳地址效率就高很多,況且C++引用的本質就是指標,只不過是const修飾地址的指標

在簡單易用和效率之間,matlab選擇了前者,C++選擇了後者

openfoam是一個非常強大的張量計算程式,既不能捨棄易用性抬高門檻,又不能反覆使用複製複製降低效率,稀疏矩陣那麼大複製來複製去算一個程式跑好幾年成本太高

openfoam使用智慧指標解決了這個問題,看起來不難讀懂又能保證效率
這也就回答了為什麼要使用智慧指標

再回到我們剛剛說的動量方程複製構造上,首先在書寫方法上依舊是matlab的顯式書寫方法,但實際上是C++的隱式移動複製
在哪裡看到用指標了,可以開啟fvm名稱空間的內容

namespace fvm
 {
 
 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
 
 template<class Type>
 tmp<fvMatrix<Type>>
 d2dt2
 (
     const GeometricField<Type, fvPatchField, volMesh>& vf
 )
 {
     return fv::d2dt2Scheme<Type>::New
     (
         vf.mesh(),
         vf.mesh().d2dt2Scheme("d2dt2(" + vf.name() + ')')
     ).ref().fvmD2dt2(vf);//這裡返回的可是fvMatrix<Type>型別指標哦
 }
 
 
 template<class Type>
 tmp<fvMatrix<Type>>
 d2dt2
 (
     const dimensionedScalar& rho,
     const GeometricField<Type, fvPatchField, volMesh>& vf
 )
 {
     return fv::d2dt2Scheme<Type>::New
     (
         vf.mesh(),
         vf.mesh().d2dt2Scheme("d2dt2(" + rho.name() + ',' + vf.name() + ')')
     ).ref().fvmD2dt2(rho, vf);
 }

 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
 
 } // End namespace fvm

看到了嘛,隨便一個fvm名稱空間下檔案,遍佈tmp智慧指標,
這裡在指標賦值時就已經完成了類的初始化,但又因為只是指標,可以用顯式的方法去寫,只要保證返回型別相同即可

fvm += fvc::surfaceIntegrate
(
	faceFlux*tinterpScheme_().correction(vf)
);

表面上是大型矩陣相加減,實際上是智慧指標這個地址在代表執行

打個比方,這就像高啟強要和趙立冬或孟德海商量一件事,趙和孟這個級別的不方便出面
出面的都是龔開疆或王秘書這樣的人,又能傳達指示又不消耗大量資源,好處就是雙方都留有餘地

王秘書見到高啟強第一句話就是,“你知道我是代表誰來的嗎”
實際在問,你知道我的哪個物件的智慧指標嗎

智慧指標智慧的點就在於不需要或者出問題的時候能自動銷燬,開啟相關解構函式

template<class T>
inline Foam::tmp<T>::~tmp()
{
    clear();
}
template<class T>
inline void Foam::tmp<T>::clear() const
{
    if (isTmp() && ptr_)
    {
        if (ptr_->unique())
        {
            delete ptr_;
            ptr_ = 0;
        }
        else
        {
            ptr_->operator--();
            ptr_ = 0;
        }
    }
}

tmp析構時對該智慧指標進行了delete,autoPtr類似

記得狂飆裡調查組一來最先銷燬的也是龔開疆這個智慧指標,,,

這樣openfoam無需g++ -o最佳化也能有很好的執行效率


autoPtr與tmp的使用場合與區別

在openfoam中,autoPtr是強引用型別智慧指標,tmp是弱引用型別智慧指標
那我們在什麼時候使用autoPtr以及tmp呢

autoPtr多使用在transport models ,boundry conditions,discretization schemes,turbulenceModel,interpolation schemes,gradient schemes或fvOptions這種動態多型中,更適合析構頻次高的地方,智慧指標autoPtr能夠自動析構,因而被廣泛使用

autoPtr<incompressible::RASModel> turbulence
(
	incompressible::RASModel::New(U, phi, laminarTransport)
);

autoPtr一旦有所指向只能移動,不能複製,同名同型別只能指向一個物件

再說tmp,之前有部落格說tmp類似shared_ptr,實際上tmp的自我介紹中並沒有像autoPtr一樣提及相關類auto_ptr,和shared_ptr也不是繼承關係,但實現功能很接近

A class for managing temporary objects.

tmp的自我介紹中說是管理臨時變數的類,這個介紹更像是我們日常做的副本,就像我現在做的部落格,害怕自己忘做份筆記,日後翻看,當然這個部落格的建立首先是自己做好了理解,因而類似的,tmp的構造需要autoPtr在前面已經做好了指定,tmp配合進行副本引用
tmp的銷燬和shared_ptr一致,具體可以見shared_ptr


一起探索openfoam也是相當有趣的一件事,非常歡迎私信討論
指正的價值要比打賞更重要,下面是個人聯絡方式,希望能結交到志同道合的朋友
image

相關文章