【发布时间】:2012-04-04 08:41:29
【问题描述】:
为方便起见,我使用以下方法。即在一个更大的程序中访问同一个 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;
}
【问题讨论】:
-
实例化另一个 myapp 会发生什么?
-
语言注释:我通常将“a = b”读作“b 分配给 a”而不是“a 分配给 b”。
标签: c++ static constructor