Created
June 25, 2013 15:01
-
-
Save jagt/5859166 to your computer and use it in GitHub Desktop.
c++ 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 <iostream> | |
#include <memory> | |
using namespace std; | |
// http://stackoverflow.com/questions/1008019/c-singleton-design-pattern | |
class Singleton | |
{ | |
public: | |
static Singleton& instance() | |
{ | |
static Singleton s; | |
// initialized on first use, guarentee to be destroyed | |
return s; | |
} | |
void foo() | |
{ | |
cout << "Singleton foo" << endl; | |
} | |
private: | |
Singleton() {}; | |
Singleton(const Singleton &s); | |
void operator = (const Singleton &); | |
}; | |
// using auto_ptr (or unique_ptr in c++11) | |
class Zingleton | |
{ | |
public: | |
static Zingleton& instance() | |
{ | |
if (_instance.get() == NULL) | |
{ | |
_instance = auto_ptr<Zingleton>(new Zingleton); | |
} | |
return *_instance; | |
} | |
void bar() | |
{ | |
cout << "Zingleton bar" << endl; | |
} | |
private: | |
static auto_ptr<Zingleton> _instance; | |
Zingleton() {} | |
Zingleton(const Zingleton &z); | |
Zingleton& operator= (const Zingleton &); | |
}; | |
// static initialization must be done in source file, or linking will have problem | |
auto_ptr<Zingleton> Zingleton::_instance = auto_ptr<Zingleton>(); | |
int main() | |
{ | |
Singleton::instance().foo(); | |
Zingleton::instance().bar(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment