Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active December 13, 2017 05:09
Show Gist options
  • Save slwu89/9b7baee2decbeaf2736a8d8d81781453 to your computer and use it in GitHub Desktop.
Save slwu89/9b7baee2decbeaf2736a8d8d81781453 to your computer and use it in GitHub Desktop.
how to access a singleton data member from another class
#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;
GlobalClass::~GlobalClass();
}
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment