Last active
February 27, 2018 22:44
-
-
Save leimao/2510d9a0a33c36d2beb1b8577fadb0b2 to your computer and use it in GitHub Desktop.
C++ singleton class example
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
// 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