Is this correct way of creating a singleton class in C++?
Possible Duplicate:
What is so bad about singletons?
Singleton pattern in C++
I want to create a singleton class. For that, I created a class with all its member and methods as static. Something like this.
class a
{
static int a;
static GetA();
}
Now all the classes who want to use my singleton class cannot create any object for my class and also will get same value. I just want to know whether this implementation will solve all the purpose and fulfill all criteria for creating a singleton class.
The conventional Singleton (anti-)pattern isn't a collection of static variables; rather, it is an object with non-static members, of which only one instance can exist.
In C++, this allows you to avoid the biggest problem with static variables: the "initialisation order fiasco". Because the initialisation order is unspecified for static variables in different translation units, there's a danger that the constructor of one might try to access another before it is initialised, giving undefined behaviour. However, it introduces other problems (a similar "destruction order fiasco", and thread safety issues in older compilers), so it's still something to avoid.
If you want a collection of static variables and functions, then put them in a namespace rather than a class:
namespace stuff {
int a;
void do_something();
}
If you think you want a singleton, then think again; you're generally better avoiding globally accessible objects altogether. If you still want one, then you would make a class with a private constructor, and a public accessor that returns a reference to the single instance, along the lines of:
class singleton {
public:
singleton & get() {
static singleton instance;
return instance;
}
int a;
void do_something();
private:
singleton() {}
~singleton() {}
singleton(singleton const &) = delete;
};
I prefer:
GlobalObjectMgr& GlobalObjectMgr::instance()
{
static GlobalObjectMgr objMgr;
return objMgr;
}
There is no class member variable required and it is created only when needed.
链接地址: http://www.djcxy.com/p/82170.html上一篇: Singleton类设计问题
下一篇: 这是用C ++创建单例类的正确方法吗?