2013-05-11 100 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