2012-05-11 69 views
0

我在讀有效的C++的建設,所以我試圖實現防止多個對象的建築類(4項):防止多個對象

#include <iostream> 
using namespace std; 


class testType 
{ 
    public: 
     testType() 
     { 
      std::cout << "TestType Ctor called." << std::endl; 
     } 
}; 

template <typename T, class C> 
class boolWrapper 
{ 
    public: 
     boolWrapper() 
      // Shouldn't T() be called here in the initialization list, before the 
      // body of the boolWrapper? 
     { 
      if (C::exists) 
      { 
       std::cout << "Oh, it exists." << endl; 
      } 
      else 
      { 
       std::cout << "Hey, it doesn't exist." << endl; 
       C::exists = true; 
       T(); 
      } 
     } 

}; 

template<class T> 
class singleton 
{ 
    private: 
     static bool exists; 
     boolWrapper<T, singleton> data_; 

    public: 
     singleton() 
      : 
       data_() 
     { 
     }; 

     friend class boolWrapper<T, singleton>; 
}; 
template <class T> 
bool singleton<T>::exists = false; 


int main(int argc, const char *argv[]) 
{ 
    singleton<testType> s; 

    singleton<testType> q; 

    singleton<testType> r; 

    return 0; 
} 

怎麼來的的T()施工boolWrapper不會在boolWrapper構造函數的主體之前調用?是否因爲boolWrapper沒有類型T的數據成員,並且它不從T繼承(沒有父類隱式調用)?

此外,我編碼沒有谷歌搜索的解決方案,我做了任何設計錯誤?

回答

1

您發佈的代碼中存在的問題是,boolWrapper沒有類型爲T的數據成員。在類構造函數中,爲基類和數據成員調用構造函數(默認值)(如果未提到顯式構造函數初始化列表)。

+0

對! (headbang)...但是如果我將T數據成員放在包裝器中,我仍然需要解決這個事實:在包裝器體被執行以便測試之前,它將首先使用包裝器類的默認構造器進行初始化如果有多個單例對象存在.... – tmaric

+0

我認爲你正在尋找單例實現。爲此,請檢查從http://stackoverflow.com/questions/1008019/c-singleton-design-pattern接受的答案作爲可能性。 –