类将指向其实例的指针作为私有成员的原因是什么

What is the reason behind a class holding a pointer to its instance as a private member?

本文关键字:成员 是什么 指针 实例      更新时间:2023-10-16

我不知道这个概念是否有名字。我有一份班级申报单;

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

如果没有更多的代码来诊断意图,它看起来很像Singleton模式的实现。

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

  • https://en.wikipedia.org/?title=Singleton_pattern
  • C++Singleton设计模式

您会发现可能有一些"get instance"方法或friend factory方法的实现。

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

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

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

我以前在Singletons中见过这种情况。

singleton是一个在内存中只能存在一次的对象。为了实现这一点,你可以通过访问器"隐藏"它的构造函数并公开它的实例(比如getInstance())。这就是为什么它保留一个指向自己的私有指针。

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

关于Singleton的教程可以在这里找到

单独使用没有任何意义。然而,如果与static A& getInstance()函数结合,它看起来更像Singleton模式。

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

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

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;
    }
};

希望能有所帮助。