0

我在文件 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 之前被初始化。解决这个问题的正确方法是什么?我已经阅读了很多关于此的文章,但我仍然感到困惑。

4

3 回答 3

1

为了清楚起见,使用静态函数的静态成员可以避免初始化顺序问题:

class x
{
 public:
     static x* get_instance()
     {
         static x* theInst = new x;
         return theInst;
     }

     void someMemberFunction();
  private:
     x() { //some code}
};

后面的代码x是这样的:

x* handle = x::get_instance();

以上是最小的,应该进一步改进以管理x生命周期。最好theImpl是静态x而不是指针x,并get_instance()返回引用而不是指针。

于 2016-06-15T11:33:12.017 回答
0

通过将其初始化为静态函数的静态成员,允许编译器在首次使用时生成单例。

此外,您可以更进一步,以零成本为您的单例对象提供值语义,同时提供以下好处:

class x
{
    struct impl
    {
        void someMemberFunction() {

        }
    };
    static impl& get_impl() {
        static impl _{};
        return _;
    }

public:
    void someMemberFunction()
    {
        return get_impl().someMemberFunction();
    }
};

int main()
{
    auto a = x();
    a.someMemberFunction();

}
于 2016-06-15T11:20:14.733 回答
0

为什么需要 x_interface 作为全局或静态实例,因为您可以使用静态方法随时随地从任何地方获取类 x 的实例:create_x_instance?

我认为在 y 类中使​​用它的最佳方法是:

(x::create_x_instance())->someMemberFunction();

于 2016-06-15T12:45:36.913 回答