饿汉模式(线程安全)
class singleton{protected:singleton(){}private:static singleton* p;public:static singleton* initance();void sayhi() {std::cout << "Hi!" << std::endl;}};singleton* singleton::p = new singleton;singleton* singleton::initance(){return p;}int main(int argc, char* argv[]) {singleton::initance()->sayhi();}
懒汉模式 (c++11保证线程安全)
class S{public:static S& getInstance(){static S instance; // Guaranteed to be destroyed.// Instantiated on first use.return instance;}private:S() {} // Constructor? (the {} brackets) are needed here.// C++ 03// ========// Don't forget to declare these two. You want to make sure they// are unacceptable otherwise you may accidentally get copies of// your singleton appearing.S(S const&); // Don't Implementvoid operator=(S const&); // Don't implement// C++ 11// =======// We can use the better technique of deleting the methods// we don't want.public:S(S const&) = delete;void operator=(S const&) = delete;// Note: Scott Meyers mentions in his Effective Modern// C++ book, that deleted functions should generally// be public as it results in better error messages// due to the compilers behavior to check accessibility// before deleted status};
全局变量析构问题
class A{public:// Get the global instance abcstatic A& getInstance_abc() // return a reference{static A instance_abc;return instance_abc;}};class B{public:static B& getInstance_Bglob;{static B instance_Bglob;return instance_Bglob;;}~B(){A::getInstance_abc().doSomthing();// The object abc is accessed from the destructor.// Potential problem.// You must guarantee that abc is destroyed after this object.// To guarantee this you must make sure it is constructed first.// To do this just access the object from the constructor.}B(){A::getInstance_abc();// abc is now fully constructed.// This means it was constructed before this object.// This means it will be destroyed after this object.// This means it is safe to use from the destructor.}};
参考
https://www.cnblogs.com/qiaoconglovelife/p/5851163.html
https://stackoverflow.com/questions/1008019/c-singleton-design-pattern
https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746
