3

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 that?
Niall
  • 30,036
  • 10
  • 99
  • 142
lulijeta
  • 900
  • 1
  • 9
  • 19

3 Answers3

4

Failing more code to diagnose the intent, it looks a lot like an implementation of the Singleton pattern.

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

You will find there is probably some implementation of a "get instance" method or a friend factory method.

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

private:
    static A* me;
};

Why is it done? To quote wikipedia

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Community
  • 1
  • 1
Niall
  • 30,036
  • 10
  • 99
  • 142
1

I have seen this before in Singletons.

A singleton is an object that can only exist once in memory. To achieve this you 'hide' its Constructor and expose it's instance my means of an accessor (like getInstance() to a private static instance of the object. This is why it keeps a private pointer to itself.

The idea is that every time some calls getInstance() you return the pointer to the static instance. This way you ensure there is only one instance for the Class.

A tutorial on Singleton's can be found here

Jose Llausas
  • 3,366
  • 1
  • 20
  • 24
1

Alone it has no significant meaning. However if coupled with a static A& getInstance() function it seems more like Singleton pattern.

Singleton pattern is basically a way to create only 1 instance of this class that is used everywhere in the program.

I prefer another way of implementing this pattern though. There is no particular reason to use this way of 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's the only place the constructor is called.
        return inst;
    }
};

Hope that helped.

DanMaklen
  • 217
  • 3
  • 9