【问题标题】:What is the reason behind a class holding a pointer to its instance as a private member?类持有指向其实例的指针作为私有成员的原因是什么?
【发布时间】:2015-09-10 07:46:32
【问题描述】:

我不知道这个概念是否有名字。我有一个班级声明;

class A
{
    public:
      ...
    private:
      static A* me;
}
  • 这是一种模式吗?
  • 为什么会有人这样做?

【问题讨论】:

  • 更多代码失败,可​​能是单例(搜索“单例模式”)?

标签: c++ class reference static private


【解决方案1】:

没有更多的代码来诊断意图,它看起来很像 单例模式的实现

stackoverflow 和维基百科上有很多参考资料;

您会发现可能有一些“获取实例”方法或友元工厂方法的实现。

class A {
public:
    static A* getInstance();
// or
    friend A* getInstance();

private:
    static A* me;
};

为什么会这样?引用维基百科

在软件工程中,单例模式是一种将类的实例化限制为一个对象的设计模式。

【讨论】:

    【解决方案2】:

    我以前在 Singletons 看到过这个。

    单例是在内存中只能存在一次的对象。为了实现这一点,你“隐藏”它的构造函数并将它的实例暴露给我的访问器(比如getInstance() 到对象的私有静态实例。这就是它保留一个指向自身的私有指针的原因。

    这个想法是每次调用getInstance() 时都会返回指向静态实例的指针。这样可以确保类只有一个实例。

    Singleton 的教程可以在here找到

    【讨论】:

      【解决方案3】:

      单独它没有任何意义。但是,如果再加上 static A& getInstance() 函数,它看起来更像是单例模式。

      单例模式基本上是一种只创建一个在程序中随处使用的类的实例的方法。

      不过,我更喜欢另一种实现这种模式的方式。除了个人喜好之外,没有特别的理由使用这种实现方式。

      class A{
      private:
          class A(){}                  //To make sure it can only be constructed inside the class.
          class A(const A&) = delete;
          class A(A&&) = delete;      //To make sure that it cannot be moved or copied
      public:
          static A& getInstance(){
              static A inst;             //That's the only place the constructor is called.
              return inst;
          }
      };
      

      希望有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-17
        • 2018-10-29
        • 2010-12-14
        • 2010-10-02
        • 2020-11-08
        • 1970-01-01
        相关资源
        最近更新 更多