Skip to content

Instantly share code, notes, and snippets.

@Santarh
Created May 24, 2012 06:29
Show Gist options
  • Save Santarh/2779810 to your computer and use it in GitHub Desktop.
Save Santarh/2779810 to your computer and use it in GitHub Desktop.
std::unique_ptr Singleton http://ideone.com/Rngaf
#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();
}
@BogdanAriton
Copy link

Hi, I'm wondering why do you have a deleter structure since the unique_ptr will delete the pointer when is no longer used?

@snehasys
Copy link

snehasys commented Jan 7, 2021

Wondering, is it thread safe?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment