我在文件 xh 中定义了一个单例类
class x
{
public:
static x* x_instance;
static x* create_x_instance
{
if(!x_instance)
x_instance = new x;
return x_instance;
}
void someMemberFunction()
private:
x() { //some code}
};
extern x *x_interface;
在 x.cpp 我有以下内容:
x *x::x_instance = 0;
x *x_interface = x::create_x_instance();
在 y.cpp 中,在另一个单例类的构造函数中,我有
x_interface->someMemberFunction();
我得到一个段错误,因为 y 在 x 之前被初始化。解决这个问题的正确方法是什么?我已经阅读了很多关于此的文章,但我仍然感到困惑。