Meyers Singleton thread safe with C++-98

拈花ヽ惹草 提交于 2019-12-24 10:47:37

问题


Currently I have this implementation of the meyer singleton:

class ClassA
{
public:
    static ClassA& GetInstance()
    {                   
        static ClassA instance;     
        return instance;
    }   

private:
    ClassA::ClassA() {};

    // avoid copying singleton
    ClassA(ClassA const&);
    void operator = (ClassA const&);
};

Now I need some improvements to getting this code thread safe in C++-98 and VS-2008?!

Thanks!

PS: What is unclear? You see the tags visual-studio-2008 and c++-98 -> so the target OS is Windows! I also don't understand why I got down voted solely some people don't like Singleton's at all!


回答1:


The Meyer singleton isn't the best solution in general, and especially not in a multithreaded environment. A more general way of implementing a singleton would be:

class ClassA
{
    static ClassA* ourInstance;
    //  ctor's, etc.
public:
    static ClassA& instance();
};

and in the source file:

ClassA* ClassA::ourInstance = &instance();

// This can be in any source file.
ClassA&
ClassA::instance()
{
    if ( ourInstance == NULL ) {
        ourInstance = new ClassA;
    }
    return *ourInstance;
}

This is thread safe if no threads are created before entering main (which should be the case), and it is not dynamically loaded (which should also be the case—if the object is to be unique, and accessible from the constructors of static objects, then it has to be their when the static constructors run). It also has the advantage of avoiding any order of destruction problems.



来源:https://stackoverflow.com/questions/17924688/meyers-singleton-thread-safe-with-c-98

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!