單例模式就是一個C++語法精華濃縮的一個體現,有句老話:麻雀雖小五臟俱全!來形容單例很是貼切!ios
下面的代碼分析了若是本身malloc而且memcpy一個單例指針會帶來很大危害並如何防止這種狀況發生。多線程
1 #include <iostream> 2 #include <cassert> 3 #include <cstdlib> 4 #include <cstring> 5 6 using std::cout; 7 using std::endl; 8 9 struct Singleton; 10 static Singleton* inst = NULL; 11 struct Singleton { 12 virtual void test_what() { 13 if (this == inst) { 14 cout << "OK, it's mine." << endl; 15 } else { 16 cout << "You go the wrong door" << endl; 17 assert(false); 18 } 19 } 20 21 void what() { 22 if (this == inst) { 23 cout << "OK, it's mine." << endl; 24 } else { 25 cout << "You go the wrong door" << endl; 26 assert(false); 27 } 28 } 29 30 void self() { 31 if (this == inst) { 32 cout << "OK, it's mine." << endl; 33 } else { 34 cout << "wtf!!!" << endl; 35 assert(false); 36 } 37 } 38 39 static Singleton* getInstance() { 40 if (NULL == inst) 41 inst = new Singleton; 42 return inst; 43 } 44 45 static void destroyInstance() { 46 if (NULL != inst) { 47 delete inst; 48 inst = NULL; 49 } 50 } 51 private: 52 Singleton() {} 53 Singleton(const Singleton&); 54 Singleton& operator=(const Singleton&); 55 }; 56 57 58 int main(int argc, char* argv[]) 59 { 60 //在程序開始就初始化,避免多線程中初始化 61 Singleton *a = Singleton::getInstance(); 62 Singleton *p = (Singleton*)malloc(sizeof(Singleton)); 63 64 memcpy(p, a, sizeof(Singleton)); 65 66 //p->self(); 67 //p->what(); 68 p->test_what(); 69 a->what(); 70 71 free(p); 72 Singleton::destroyInstance(); 73 74 return 0; 75 }
總結:函數
一、以上單例是比較常見的實現this
二、memcpy會破壞這個單例的惟一性spa
三、memcpy出來的對象對公有虛函數,公有成員函數均可以正常訪問,由於C++類成員函數地址是共享的,可經過this指針檢查是否惟一線程