问题
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