What is the reason that a class holds a pointer to its instance as a private member?

I don't know if this concept has a name. I have a class declaration;

class A
{
    public:
      ...
    private:
      static A* me;
}

      

  • Is this a pattern?
  • Why would anyone do this?
+3


source to share


3 answers


Having no more code to diagnose intent, it is very similar to the implementation of the Singleton pattern.

There is a lot of reference material available here on stackoverflow and wikipedia;

You will find that there is probably an implementation of a get instantiated method or a friend's factory method.



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

private:
    static A* me;
};

      

Why is this being done? To quote wikipedia

In software development, a singleton pattern is a design pattern that restricts instantiation of a class to a single object .

+4


source


I've seen this before in Singletons

.

Syntax is an object that can only exist once in memory. To do this, you "hide" your constructor and expose it to an instance of my accessors (for example, getInstance()

to a private static object instance. That's why it stores a private pointer to itself.



The idea is that every time some calls getInstance()

you return a pointer to a static instance. This way you ensure there is only one instance for the class.

The Singleton tutorial can be found here

+1


source


Alone, this doesn't really matter. However, if combined with a function static A& getInstance()

it looks more like a Singleton pattern.

The Singleton pattern is basically a way to create just one instance of this class, which is used throughout the program.

I prefer another way to implement this pattern. There is no particular reason to use this implementation other than personal preference.

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 the only place the constructor is called.
        return inst;
    }
};

      

Hope it helped.

+1


source







All Articles