Last active
August 29, 2015 14:08
-
-
Save qzchenwl/84ed1c301b4d01505988 to your computer and use it in GitHub Desktop.
Single instance base class for C++.
This file contains hidden or 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 <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; | |
} |
This file contains hidden or 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
#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