Russian-Chinese style
#include <iostream>using namespace Std;class a{public:static a& getinstance (void) {return s_instance; }private:a (int data=0): m_data (data) {} A (a const& that); int m_data; Static A s_instance;}; A a::s_instance (1234); int main (void) {a& A1 = A::getinstance (); a& A2 = A::getinstance (); cout << &a1 << ', ' << &a2 << Endl; return 0;}
This is a singleton with static members.
Because it is a singleton, it is forbidden to create another class A object, and a calls the constructor to create the object, so the class A constructor is placed in the
Private, a A = A::getinstance () calls the copy constructor to create the object, so the copy constructor is placed in private
The interface function static a& getinstance (void), is static, and if non-static, then how to call getinstance
function, so it has to be static.
Note: Static member Object S_instance is a private constructor that can be called (and I don't know why).
2. Lazy Type
#include <iostream>using namespace std;class a{public: static a& getinstance (void) { if (!s_instance) { s_instance = new a (1234 ); } return *s_instance; } void release (void) { if (s_counter && --s_counter==0) { delete this; s_instance = NULL; } }private: ~a (void) {} a (int data = 0): m_data (data) {} a (a const& that); int m_data; static int s_counter; static A* s_instance;}; int a::s_counter = 0; A* a::s_instance = null;int main (void) { a& a1 = A::getinstance (); a& a2 = a::getinstance (); cout << &a1 << ', ' << &a1 << endl; a1.release (); a2.release (); return 0;}
Here is a static member pointer as a singleton, there is nothing to say.
Note: The static member Pointer S_instance, the constructor is called at New A (1234), but when you delete this, the function is not called, whether it is a public destructor or a private destructor (why you cannot call the destructor I don't know)
This article is from the "12208412" blog, please be sure to keep this source http://12218412.blog.51cto.com/12208412/1866052
Two single cases of C + + (a hungry man, lazy type)