Skip to content

Instantly share code, notes, and snippets.

@leimao
Last active February 27, 2018 22:44
Show Gist options
  • Save leimao/2510d9a0a33c36d2beb1b8577fadb0b2 to your computer and use it in GitHub Desktop.
Save leimao/2510d9a0a33c36d2beb1b8577fadb0b2 to your computer and use it in GitHub Desktop.
C++ singleton class example
// Source: https://sourcemaking.com/design_patterns/singleton/cpp/1
class GlobalClass
{
int m_value;
static GlobalClass *s_instance;
GlobalClass(int v = 0)
{
m_value = v;
}
public:
int get_value()
{
return m_value;
}
void set_value(int v)
{
m_value = v;
}
static GlobalClass *instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
};
// Allocating and initializing GlobalClass's
// static data member. The pointer is being
// allocated - not the object inself.
GlobalClass *GlobalClass::s_instance = 0;
void foo(void)
{
GlobalClass::instance()->set_value(1);
cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
}
void bar(void)
{
GlobalClass::instance()->set_value(2);
cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
}
int main()
{
cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
foo();
bar();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment