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:
- How is this behavior implemented ?
- 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?