c++单例模式代码分析

单例模式就是一个C++语法精华浓缩的一个体现,有句老话:麻雀虽小五脏俱全!来形容单例非常贴切!

下面的代码分析了如果自己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 }

 

总结:

1、以上单例是比较常见的实现

2、memcpy会破坏这个单例的唯一性

3、memcpy出来的对象对公有虚函数,公有成员函数都可以正常访问,因为C++类成员函数地址是共享的,可通过this指针检查是否唯一

posted @ 2017-03-24 12:23  丹西  阅读(330)  评论(0编辑  收藏  举报