胡乱写的一些代码,感觉应该有一定的用处,可是还没有想好用在什么情况下,赠与有缘人。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
#include "new" using namespace std; class COneInstance { typedef COneInstance thisClass; int* _piCount; public: COneInstance() { static bool bConstructing = false; if(bConstructing) return; bConstructing = true; thisClass* p = new thisClass; if(p != NULL) delete p; bConstructing = false; if(this != p) // you [may] allocate this object on stack throw bad_alloc(); if(*_piCount == 1) // the very first instance { /// TODO: do some thing printf("Aha, the first constructing!\n"); } } void* operator new(size_t size) { static int iCount = 0; static void* pOnlyInstance = NULL; void* p = NULL; if(iCount == 0) { p = ::operator new(size); pOnlyInstance = p; } else { p = pOnlyInstance; } if(p != NULL) { iCount++; ((thisClass*)p)->_piCount = &iCount; } return p; } void operator delete(void* p) { if(p == NULL) return; int& riCount = *((thisClass*)p)->_piCount; riCount--; if(riCount == 0) ::operator delete(p); } private: void* operator new[](size_t size); void operator delete[](void* p); }; typedef COneInstance COneInstanceOnHeap; class COneInstanceOnStack { public: COneInstanceOnStack() { static int iCount = 0; if(iCount != 0) throw bad_alloc(); iCount++; } private: void* operator new(size_t size); void operator delete(void* p); void* operator new[](size_t size); void operator delete[](void* p); }; void TestOneInstance() { COneInstanceOnHeap* pooh1 = new COneInstanceOnHeap; COneInstanceOnHeap* pooh2 = new COneInstanceOnHeap; printf("COneInstanceOnHeap instance 1: 0x%p\n", pooh1); printf("COneInstanceOnHeap instance 2: 0x%p\n", pooh2); delete pooh1; delete pooh2; try { COneInstanceOnHeap ooh; } catch(bad_alloc& /*rba*/) { printf("we wanna place a COneInstanceOnHeap instance on stack, so exception fired!\n"); } COneInstanceOnStack oos1; try { COneInstanceOnStack oos2; } catch(bad_alloc& /*rba*/) { printf("we wanna place a COneInstanceOnStack instance on stack again, so exception fired!\n"); } // You cannot do this, the compiler will stop you... // COneInstanceOnStack* poos = new COneInstanceOnStack; } |