0
class X 
{
private:
    static X* obj;
    X(){};
public:
    static X* setObj();
    static void removeObj();
};

X* X::obj = nullptr;

X* X::setObj()
{
    if ( obj == nullptr )
    obj = new X;
    return obj;
}

void X::removeObj()
{
    delete obj;
    obj = nullptr;
}

Can't exactly understand what the class and the functions does, so far I had is it will create an object is none is created?

  • 2
    Looks like a poorly designed [Singleton implementation](https://en.wikipedia.org/wiki/Singleton_pattern). Click [here for a better one](https://stackoverflow.com/a/1008289/4581301). – user4581301 Dec 02 '20 at 07:08

1 Answers1

3

It's a Singleton, but it's got the potential to be buggy in multi-threaded usage. This is the correct way to do it in C++11 - names changed to match your code:

X &getObj()
{
    static X inst(...);
    return inst;
}

No need to explicitly delete the object since the runtime will do it automatically on shutdown.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • 1
    Since there's only a few lines of code in the linked answer, you might as well paste it here as well. – cigien Dec 02 '20 at 07:18