2013-05-11 94 views

回答

0

這樣做的典型方法是將你的靜態對象包裝在一個getter函數中,這樣它就不會在第一次使用之前不會被創建。

這樣,順序是由程序的設計決定的。

該方案的一個例子是以下幾點:

class MyClass { 
    public: 
    static 
    MyContainer& GetTheContainer() { 
     static MyContainer* fgCon = new MyContainer; // happens at first demand 
     return *fgCon; // happens whenever MyClass::GetTheContainer() is called 
    } 

    static 
    SomeObj& GetFromContainerAt(const int i) { 
     MyContainer& c = GetTheContainer(); 
     return c.At(i); 
    } 
}; 

其餘的取決於你的程序的設計。您可以讓其他類填充容器 - 只要他們使用GetTheContainer,就可以確保容器將首先製成。

 MyContainer& GetTheContainer() { 
     static MyContainer* fgCon = new MyContainer; // happens at first demand 
     static bool isNew = true; // only true the first time 
     if (isNew) { 
      // fill the container 
      isNew = false; 
     } 
     return *fgCon; // happens whenever MyClass::GetTheContainer() is called 
    } 

你可以閱讀更多:或者你可以在它的創作,無論是通過檢查,如果它是空的(如果你相信它會永遠只能是在創建空的),或者通過使用標誌系統填充容器例如,關於該方案在C++ Faq

+1

請注意,即使您有一堆已經直接使用某個靜態對象的代碼,也可以使用它。只需找到靜態對象的聲明位置,用上面的getter替換它,然後使用'#define(GetTheStaticObject())theOldObjectVariable'。這樣,所有的對象都被預編譯器的getter替換。我之前使用過這個技巧,發現它非常方便! – Corey 2013-05-11 05:54:52

+1

交換#define中的標記 - 它應該讀取#define theOldObjectVariable(GetTheStaticObject()),但我討厭通過預解析器靜靜地竊取代碼。 – franji1 2013-05-11 05:59:09

+0

啊,你是對的,謝謝!不過,編輯評論已經太遲了。 (至於預編譯器 - 我不想提倡它太多,但比編輯數百個文件要容易...) – Corey 2013-05-11 06:03:08