静态成员仅在使用类时初始化

时间:2012-11-05 20:04:16

标签: c++ static static-members

  

可能重复:
  How to force a static member to be initialized?
  How to automatically register a class on creation

我有一个类应该在Factory中注册她的create方法,这样我就可以使用工厂创建这个类了。但是,只有在main方法中实例化类时,初始化才有效。

这是我要注册的课程:

class CDESolverD2Q5 : public CDESolver
{
public:

    static CDESolver* create()
    {
        return new CDESolverD2Q5;
    }
private:
    static const std::string name_;
    /**
     * @brief registered_ if true then class is registered w/ Solver Factory
     */
//only for accessing this element from the main method
public:
    static const bool registered_;
    /**
     * @brief registerLoader Registers the Solver with the factory.
     * @return A boolean that indicates if the registration was successful
     */
    static bool registerLoader();

};

这里是cpp文件中的代码:

const std::string CDESolverD2Q5::name_ = "CDESolverD2Q5";


bool CDESolverD2Q5::registerLoader()
{
    return SolverFactory.registerType(CDESolverD2Q5::name_, CDESolverD2Q5::create);
}

const bool CDESolverD2Q5::registered_ = CDESolverD2Q5::registerLoader();

这里是我工厂的registerType方法:

bool registerType(const IdentifierType& id,
                      ProductCreatorSignature creator)
    {
        return productMap_.insert(typename ProductMap::value_type(id, creator)).second;
    }

但是,如果我在main方法中访问静态成员,则初始化静态成员:

int main(int argc, char* argv[]) {
    //how can I avoid the next line?
    bool blub = CDESolverD2Q5::registered_;

    CdeSolver* solver =SolverFactory.createObject("CDESolverD2Q5");
}

如果我删除了行bool blub = CDESolverD2Q5::registered_;该类未在我的工厂注册。但我认为静态成员在执行main方法之前自动初始化,那么为什么我需要这一行呢?我怎么能避免这一行?

0 个答案:

没有答案