2

目前我有这个迈耶单例的实现:

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

private:
    ClassA::ClassA() {};

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

现在我需要一些改进来让这个代码在 C++-98 和 VS-2008 中线程安全?!

谢谢!

PS:什么不清楚?您会看到标签 visual-studio-2008 和 c++-98 -> 所以目标操作系统是 Windows!我也不明白为什么我投了反对票,只是有些人根本不喜欢 Singleton 的!

4

1 回答 1

5

Meyer 单例通常不是最好的解决方案,尤其是在多线程环境中。实现单例的更通用方法是:

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

并在源文件中:

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.

于 2013-07-29T13:56:18.267 回答