Created
May 24, 2012 06:29
-
-
Save Santarh/2779810 to your computer and use it in GitHub Desktop.
std::unique_ptr Singleton http://ideone.com/Rngaf
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 <memory> | |
class Hoge | |
{ | |
public: | |
static Hoge& GetInstance(); | |
void Hey() | |
{ | |
std::cout << foo << std::endl; | |
} | |
void SetFoo( int a ) | |
{ | |
foo = a; | |
} | |
private: | |
Hoge() : foo(0) {}; | |
Hoge( const Hoge& a ) {}; | |
~Hoge() {}; | |
struct hoge_deleter; | |
int foo; | |
}; | |
struct Hoge::hoge_deleter | |
{ | |
void operator()( const Hoge* const p ) | |
{ | |
std::cout << "Hoge deleter" << std::endl; | |
delete p; | |
} | |
}; | |
Hoge& Hoge::GetInstance() | |
{ | |
static std::unique_ptr<Hoge, hoge_deleter> instance( new Hoge() ); | |
return *instance; | |
} | |
int main() | |
{ | |
Hoge& hoge1 = Hoge::GetInstance(); | |
hoge1.SetFoo( 2 ); | |
Hoge& hoge2 = Hoge::GetInstance(); | |
hoge1.Hey(); | |
hoge2.Hey(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I'm wondering why do you have a deleter structure since the unique_ptr will delete the pointer when is no longer used?