Skip to content

Instantly share code, notes, and snippets.

@h0hmj
Created March 15, 2018 07:41
Show Gist options
  • Save h0hmj/09bff9ca98fe7c4cdaa0e93875bf3a46 to your computer and use it in GitHub Desktop.
Save h0hmj/09bff9ca98fe7c4cdaa0e93875bf3a46 to your computer and use it in GitHub Desktop.
double checked locking singleton
#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