C++再论单例模式
2015-07-11 15:45
323 查看
#include <iostream> #include <windows.h> #include <mutex> std::mutex gmutex; using namespace std; template<typename Type> class Singleton { public: static Type* GetSingleton() { if (siglen == NULL) { unique_lock<std::mutex> lock(gmutex);//C++11加锁。 if (siglen == NULL) { siglen = new Type(); Type *temp = new Type(); MemoryBarrier(); siglen = temp; } } return siglen; } private: static Type* siglen; }; template<typename Type> Type* Singleton<Type>::siglen = NULL; class Text { public: Text() { data = 100; //因为是单例模式,所以唯一会出现申请内存,调用构造 //函数,赋值三个步骤混乱的机会只有在前面的1-2次 //的时候,可惜速度太快了,这种情况发生的概率及其低 //,但是我们的心理要始终明白。 } void Printf() { cout << "data="<<data << endl; } static DWORD WINAPI ThreadFunc(LPVOID arg) { Singleton<Text>::GetSingleton()->Printf(); return DWORD(0); } private: int data; }; int main() { HANDLE hThread; DWORD threadId; for (int i = 0; i < 10; i++) { hThread = CreateThread(NULL, 0, &(Text::ThreadFunc), (void *)"123",0, &threadId); } Sleep(5); cout << "ThreadFunc is running!!!" << endl; return 0; } #include <iostream> using namespace std; //引用计数的智能指针。 template<typename Type> class my_auto_ptr { public: my_auto_ptr(Type* p = NULL) :ptr(p) { count = new int[1]; count[0] = 1; } my_auto_ptr(const my_auto_ptr &ma) { count = ma.count; count[0]++; } my_auto_ptr& operator=(const my_auto_ptr &ma) { if (this != &ma) { this->~my_auto_ptr(); count = ma.count; count[0]++; ptr = ma.ptr; } return *this; } ~my_auto_ptr() { if (count!=NULL &&count[0]-- == 1) { cout << "~my_auto_ptr()" << endl; delete ptr; ptr = NULL; delete[] count; count = NULL; } } Type* operator->() { return ptr; } Type& operator*() { return *ptr; } private: Type *ptr; int *count; }; int main() { my_auto_ptr<int> ps(new int(100)); my_auto_ptr<int> pb(ps); my_auto_ptr<int> pd; pd = pb; return 0; }
相关文章推荐
- C++实现简单遗传算法
- 【err】non-POD类对象的文件读写
- Java数组与c++数组的区别
- C++多线程编程
- C++ 设计三法则 二法则
- C++中关于const的一些使用惯例
- C语言文件操作之fgets()
- 关于C语言书籍推荐:深入学习c语
- 一个简单顺序表的C++实现
- c++隐藏文件
- 【c++】简单的string类的几个基本函数
- c++隐藏文件
- c++ :0x00e08b47 处有未经处理的异常: 0xC00000FD: Stack overflow
- C语言32个关键字总结以及C++几个常用关键字
- [cernRoot]how to get tree name?
- c++primer要点-模板与泛型编程
- C语言运算符优先级与结合方向
- C++再次理解虚表
- chapter17test3
- C语言中给数组赋随机值