0

When memory will be created for myClass object pointed by ptr? Is below singleton thread safe?

Class myClass
{
    static myClass* ptr;
public:
    myClass(){}
    ~myClass(){}

    static myClass* getPtr();

};

myClass* myClass::ptr = new myClass();

myClass* myClass::getPtr()
{
   return ptr;
}

int main()
{
    myClass* temp = myClass::getPtr();
    return 0;
}
JBL
  • 12,588
  • 4
  • 53
  • 84
NDestiny
  • 1,133
  • 1
  • 12
  • 28

1 Answers1

2

When memory will be created for myClass object pointed by ptr ??

During the dynamic initialisation stage, before main begins. Beware the initialisation order fiasco: it might not be created before other static variables in other translation units, so you might have big problems if their initialisers try to access it.

is below single tone thread safe ??

If you don't start any threads before main begins, then yes. If another static variable's initialiser starts a thread, then maybe not.

I would recommend you avoid global variables altogether, whether or not you try to disguise them as singletons. It's difficult implement that anti-pattern safely and correctly in C++. (I would say impossible, since I don't know of any way to do it, but according to the comments someone knows better than me.)

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Just a nit concerning the second paragraph: things get more complicated when dynamic loading is involved, and static objects in explicitly loaded objects (i.e. with `dopen` or `LoadLibrary`) will not be initialized until the library is loaded. – James Kanze Dec 11 '14 at 13:29
  • And while global variables and singletons can be abused, there are a few cases where they are the appropriate solution (and they can be implemented correctly and safely). – James Kanze Dec 11 '14 at 13:31
  • @JamesKanze: Indeed, I was just talking about this particular case (in the same translation unit as `main`), and didn't want to complicate the answer by trying to cover all the freaky edge cases. I disagree that singletons can be implemented safely and correctly (unless you regard a memory leak as "correct"), but that's been discussed to death elsewhere and is off-topic here. – Mike Seymour Dec 11 '14 at 13:42
  • Yes. That's why I said it was just a nit. Covering all of the special cases would require at least a couple of pages, and someone just beginning probably wouldn't be able to understand most of it anyway. (And despite your claims, many people, myself included, have implemented singletons safely and correctly.) – James Kanze Dec 11 '14 at 15:32
  • @JamesKanze: OK, I'll take your word that it's not impossible and tone down my language. I've seen many attempts, but none which don't involve either a memory leak or the possibility of access outside the object's lifetime; but I'm not particularly interested in how you worked around these issues, since all the other reasons to avoid the anti-pattern still apply. – Mike Seymour Dec 11 '14 at 15:43