#include Class test {static test * pinstance; protected: public: test () {if (! pinstance) {pinstance = 0;} printf ("testin / n");} void * operator new Unsigned int size) {if (! pinstance) {pinstance = (test *) :: Operator new (sizeof (test));} return (void *) pinstance;} int a;}; test * test :: pinstance = null ; #ifndef __no_unit_test__int main () {Printf ("Singleton Pattern Test / N"); Test * Pt = New Test (); test * pt2 = new test (); Printf ("% D,% D / N", PT -> aa, pt2-> aa); Pt-> aa = 123; Printf ("% D,% D / N", PT-> AA, PT2-> AA); test * pt3 = new test (); printf ("% D,% D,% D / N", Pt-> aa, pt2-> aa, pt3-> aa); return 0;} # ENDIF
Disadvantages: You can only construct the object by New's way, you cannot construct on the stack