-1
    static CMyStatic* myStatic = nullptr;


    CMyStatic* CMyStatic::getInstance(){
        if(myStatic==nullptr)
                myStatic = new CMyStatic;
        return myStatic;
    }

if I make singleton, in getInstance() function,

check class pointer is null. like this code.

I understandiong static object is only making one, isn't it?

then, if i didn't check myStatic==nullptr,

always make myStatic = new CMyStatic,

myStatic isn't making, isn't it?

or my understanding is wrong?

D.A.KANG
  • 265
  • 2
  • 4
  • 12
  • I think you're understanding wrong. If you had `static CMyStatic* myStatic = new CMyStatic`, then that would only construct it once – Tas Oct 26 '18 at 02:43
  • For a thread safe singleton, check out the Myers singleton https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton – Michael Surette Oct 26 '18 at 02:45
  • I prefer using a static local variable instead: `CMyStatic* CMyStatic::getInstance(){ static CMyStatic myStatic; return & myStatic; }` – Remy Lebeau Oct 26 '18 at 03:05

1 Answers1

2

If you always create a new CMyStatic then any state held by the old one is lost. If you don't need state to be maintained then you don't really need a Singleton at all - just a class with some static methods.

By doing a null check you create one object the first time it is needed and from then on you always use the same object which can keep some state information between calls.

In some cases you may want to create the object all the time and not just "as needed" - in this case you could get away without the null check because you don't expect it to ever be null.

John3136
  • 28,809
  • 4
  • 51
  • 69