Skip to content

Instantly share code, notes, and snippets.

@qzchenwl
Last active August 29, 2015 14:08
Show Gist options
  • Save qzchenwl/84ed1c301b4d01505988 to your computer and use it in GitHub Desktop.
Save qzchenwl/84ed1c301b4d01505988 to your computer and use it in GitHub Desktop.
Single instance base class for C++.
#include <iostream>
#include "single_instance.hpp"
using namespace std;
class A : public enable_single_instance<A>
{
friend class enable_single_instance<A>;
public:
void echo()
{
cout << this << endl;
}
~A()
{
cout << __FUNCTION__ << endl;
}
private:
A()
{
cout << __FUNCTION__ << endl;
}
};
int main(int argc, char* argv[])
{
A::single_instance().echo();
A::single_instance().echo();
A::single_instance().echo();
return 0;
}
#pragma once
#include <memory>
#include <mutex>
template <typename T>
class enable_single_instance
{
friend T;
public:
static T& single_instance()
{
std::call_once(_flag, [&]{ _instance.reset(new T()); });
return *_instance;
}
private:
enable_single_instance() {};
private:
static std::unique_ptr<T> _instance;
static std::once_flag _flag;
};
template <typename T> std::unique_ptr<T> enable_single_instance<T>::_instance;
template <typename T> std::once_flag enable_single_instance<T>::_flag;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment