Here is a simple implementation of singleton,
By debugging, I found that a1._x = 1 and a2._x = 1. It looks like only one object is created. But I wonder why returning static object a can guarantee only one object is created.Code:class A { private: A(int x) : _x(x) { } int _x; friend A& createA(int x) { static A a(x); return a; } }; int main() { A a1 = createA(1); A a2 = createA(2); return 0; }




Reply With Quote