I am using the approach below for convenience. ie a convenient means of accessing the same myapp instance in a larger program. The code compiles and runs correctly on my machine but want to ask if anyone sees any problems with this approach?
For example, the this ptr is assigned to the_app in the constructor? Is that ok? My concern is that object is still being constructed. but if last line of constructor then ok? Or is it because it is a pointer so doesn't matter because as long as used when fully constructed will be ptr to full object?
#include <iostream>
using namespace std;
class myapp
{
public:
myapp() : m_data(0)
{
the_app = this;
}
void DoIt() { cout << "doing it\n"; }
static myapp* the_app;
private:
int m_data;
};
myapp* myapp::the_app = 0;
int main(int argc, char* argv[])
{
myapp app;
app.DoIt(); //doing it using member function
myapp::the_app->DoIt(); //accessing using static ptr
return 0;
}