Skip to content

Instantly share code, notes, and snippets.

@raytroop
Last active December 3, 2019 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raytroop/c4f99b1235b8394f9424c1b56d3bd6ff to your computer and use it in GitHub Desktop.
Save raytroop/c4f99b1235b8394f9424c1b56d3bd6ff to your computer and use it in GitHub Desktop.
Singleton design pattern
class Singleton{
private:
Singleton();
Singleton(const Singleton& other);
public:
static Singleton* getInstance();
static Singleton* m_instance;
};
Singleton::Singleton() {}
Singleton* Singleton::m_instance=nullptr;
//线程非安全版本
Singleton* Singleton::getInstance() {
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
//线程安全版本,但锁的代价过高
Singleton* Singleton::getInstance() {
Lock lock;
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment