2

I encountered a behavior I didn't understand.

Here is test code of a common singleton implementation,

Code from the link:

#include <iostream>

using namespace std;

class CFoo
{
public:
  static CFoo & instance ()
  {
    static CFoo instance;
      return instance;
  }
private:
    CFoo ()
  {
    cout << "CFoo();" << endl;
  }
};

int
main ()
{
  cout << "main() enter" << endl;
  CFoo & foo1 = CFoo::instance ();
  cout << "got foo1 @ " << &foo1 << endl;

  CFoo & foo2 = CFoo::instance ();
  cout << "got foo2 @ " << &foo2 << endl;

  cout << "main() leave" << endl;
  return 0;
}

Notice that static (CFoo) inside function (instance()) are initialized only on first call to the function (after Main() enter).

This behavior confused me as I thought the static would be initiated during bring-up (pre-main) phase. Also, This seem unorthodox for c++ because the only I can think of to implement this is by adding a "hidden" condition to check for "first entry".

I have two questions:

  1. How is this behavior implemented ?
  2. If there is a hidden branch: Is the code thread safe?
    or can there be two different instances if several threads accessed the method simultaneously?
Vagish
  • 2,520
  • 19
  • 32
Tomer W
  • 3,395
  • 2
  • 29
  • 44
  • 1. There is a constructor call necessary to construct `instance` with `CFoo::CFoo()`. AFAIK, this constructor has to be called before first usage. 2. Have a look at [SO: C++ Meyers Singleton - thread safe (code equivalent for mutex?)](https://stackoverflow.com/a/34001592/7478597) and [SO: Is Meyers' implementation of the Singleton pattern thread safe?](https://stackoverflow.com/a/1661564/7478597). – Scheff's Cat May 14 '19 at 05:34
  • @Scheff thanks, i think that makes my question kind of a duplicate. – Tomer W May 14 '19 at 05:38
  • Probably two duplicates. I guess the 1. part is handled somewhere else... ;-) – Scheff's Cat May 14 '19 at 05:40
  • Found one: [SO: When exactly is constructor of static local object called?](https://stackoverflow.com/a/3063103/7478597) (which is a dupe itself). – Scheff's Cat May 14 '19 at 05:42

0 Answers0