Created
March 15, 2018 07:41
-
-
Save h0hmj/09bff9ca98fe7c4cdaa0e93875bf3a46 to your computer and use it in GitHub Desktop.
double checked locking singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include "Mutex.h" | |
#include "NonCopyable.h" | |
template <typename T> | |
class Singleton : NonCopyable { | |
public: | |
static T& instance() { | |
if (val_ == NULL) { | |
MutexLockGuard lock(mutex_); | |
if (val_ == NULL) { | |
val_ = new T(); | |
std::atexit(destroy); | |
} | |
} | |
return *val_; | |
} | |
private: | |
Singleton(); | |
~Singleton(); | |
static void destroy() { delete val_; } | |
Mutex mutex_; | |
static T* val_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment