为方便起见,我使用以下方法。即在一个更大的程序中访问同一个 myapp 实例的一种方便的方法。代码可以在我的机器上正确编译和运行,但想问是否有人发现这种方法有任何问题?
比如 this ptr 是在构造函数中赋值给 the_app 的?那样行吗?我担心的是对象仍在构建中。但是如果构造函数的最后一行那么好吗?还是因为它是一个指针所以没关系,因为只要在完全构造时使用就会指向完整对象?
#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;
}