Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class GlobalClass
- {
- int m_value;
- static GlobalClass *s_instance;
- GlobalClass(int v = 0){
- std::cout << "global singleton being born at " << this << std::endl;
- m_value = v;
- };
- ~GlobalClass(){
- std::cout << "global singleton being killed at " << this << std::endl;
- };
- public:
- int get_value()
- {
- return m_value;
- }
- void set_value(int v)
- {
- m_value = v;
- }
- void kill_me(){
- std::cout << "global singleton is dying!" << std::endl;
- delete this;
- }
- 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 = nullptr;
- class accessor {
- public:
- accessor(int _id) : id(_id){std::cout << "birthing accessor: " << id << std::endl;};
- ~accessor(){std::cout << "killing accessor: " << id << std::endl;};
- void get_par(){
- std::cout << "im accessing the global thing " << GlobalClass::instance()->get_value() << std::endl;
- };
- private:
- int id;
- };
- void foo(void)
- {
- std::cout << "entering foo" << std::endl;
- std::cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
- GlobalClass::instance()->set_value(1);
- std::cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
- std::cout << "exiting foo" << std::endl;
- }
- void bar(void)
- {
- std::cout << "entering bar" << std::endl;
- std::cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
- GlobalClass::instance()->set_value(2);
- std::cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
- std::cout << "exiting bar" << std::endl;
- }
- int main()
- {
- std::cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << std::endl;
- GlobalClass::instance()->set_value(5);
- accessor* accessor1 = new accessor(1);
- accessor1->get_par();
- foo();
- bar();
- delete accessor1;
- std::cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << std::endl;
- GlobalClass::instance()->kill_me();
- }
Add Comment
Please, Sign In to add comment