A implementation method of Singleton mode in C ++

xiaoxiao2021-03-06  15

#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

转载请注明原文地址:https://www.9cbs.com/read-48627.html

New Post(0)