新聞中心
在C#中,類的靜態(tài)構(gòu)造函數(shù)用于在使用類之前進行相關(guān)的初始化工作;比如,初始化靜態(tài)成員或執(zhí)行特定操作。CLR 在***次創(chuàng)建該類對象或調(diào)用該類靜態(tài)方法時自動調(diào)用靜態(tài)構(gòu)造函數(shù)。同時,CLR保證靜態(tài)構(gòu)造函數(shù)的線程安全性(準確地說是,只會調(diào)用一次,不存在多線程問題)。

創(chuàng)新互聯(lián)是一家專注于網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計與策劃設(shè)計,上街網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:上街等地區(qū)。上街做網(wǎng)站價格咨詢:18982081108
下面是MSDN對靜態(tài)構(gòu)造函數(shù)特點的描述:
1.靜態(tài)構(gòu)造函數(shù)既沒有訪問修飾符,也沒有參數(shù)
2.在創(chuàng)建***個實例或引用任何靜態(tài)成員之前,將自動調(diào)用靜態(tài)構(gòu)造函數(shù)來初始化類
3.無法直接調(diào)用靜態(tài)構(gòu)造函數(shù)
4.在程序中,用戶無法控制何時執(zhí)行靜態(tài)構(gòu)造函數(shù)
C++語言規(guī)范并未包含類似靜態(tài)構(gòu)造函數(shù)的東西,但在使用類之前做初始化工作的需求卻是客觀存在的。就滿足需求本身來講,C++完全可以通過手動方式實現(xiàn),但要處理好初始化時機,線程安全性等問題。本文則嘗試通過C++的模版機制模擬實現(xiàn)靜態(tài)構(gòu)造函數(shù),避免手動初始化的繁瑣實現(xiàn)。對于需要靜態(tài)構(gòu)造函數(shù)的類A,只需用繼承static_constructable模版類,并提供 static void statici_constructor()靜態(tài)方法即可:
- class A : static_constructable
- {
- public:
- static void static_constructor() {
- std::cout << “static constructor a” << std::endl;
- s_string = “abc”; //初始化靜態(tài)數(shù)據(jù)
- }
- static std::string s_string;
- public:
- A(){
- std::cout << “constructor a” << std::endl;
- }
- private:
- int m_i;
- };
- std::string A::s_string;
- int _tmain(int argc, _TCHAR* argv[]){
- std::cout << “beginning of main” << std::endl;
- assert(sizeof(A) == sizeof(int));//繼承不改變A的內(nèi)存布局
- assert(A::s_string == ““);
- A a1;
- assert(A::s_string == “abc”);
- A a2;
- std::cout << “end of main” << std::endl;
- return 0;
- }
輸出:
- beginning of main
- static constructor a //創(chuàng)建A對象前自動調(diào)用靜態(tài)構(gòu)造方法,一次且僅一次
- constructor a
- constructor a
- end of main
下面是static_constructable類模板的實現(xiàn):
- template
- class static_constructable
- {
- private:
- struct helper{
- helper(){
- T::static_constructor();
- }
- };
- protected:
- static_constructable(){
- static helper placeholder;
- }
- };
上面的實現(xiàn)把對A::static_constructor()的回調(diào)放到內(nèi)部類helper的構(gòu)造函數(shù)中;并在static_constructable()中定義一個helper局部靜態(tài)變量;C++保證在構(gòu)造派生類 A的對象時,會先調(diào)用基類static_constructable的構(gòu)造函數(shù),且靜態(tài)局部變量只會構(gòu)造一次,這樣就達到調(diào)用一次且僅一次A::static_constructor()的目的。
static_constructor類模板簡單地模擬了C#的靜態(tài)構(gòu)造函數(shù)機制,它具有以下特點:
1. 在***次構(gòu)造類對象之前自動調(diào)用類提供的靜態(tài)構(gòu)造函數(shù)
2. 靜態(tài)構(gòu)造函數(shù)被調(diào)用的時機是確定的
3. 利用了C++的局部靜態(tài)變量初始化機制保證了線程安全性(更正:實際并非線程安全,C++標準不涉及多線程問題,而一般編譯器實現(xiàn)也非線程安全,更多參見評論部分)
4. 基于繼承的實現(xiàn)機制并未改變派生類的對象內(nèi)存布局
不過,和本文開始列出的C#靜態(tài)構(gòu)造函數(shù)的幾個特點相比,本實現(xiàn)還有明顯的不足:無法通過調(diào)用類A的靜態(tài)方法觸發(fā)靜態(tài)構(gòu)造函數(shù);類A的靜態(tài)構(gòu)造函數(shù)必須是public的。
【編輯推薦】
- Visual C++中實現(xiàn)對圖像數(shù)據(jù)的讀取顯示
- 淺談怎樣加快C++代碼的編譯速度
- C++和Java 的缺省初始化問題
- C++中基類對象安全轉(zhuǎn)換為派生類對象的方法
- C++設(shè)計目標及原則
本文題目:淺析C#與C++在靜態(tài)構(gòu)造函數(shù)上的異同
網(wǎng)址分享:http://www.5511xx.com/article/dhdpehc.html


咨詢
建站咨詢
