一种智能指针的实现方式
来源:互联网 发布:电信宽带网络线路故障 编辑:程序博客网 时间:2024/05/01 16:27
#include<iostream>#include<stdexcept>using namespace std;#define TEST_SMARTPTRclass Stub{public:void print(){cout << "Stub:print" << endl;}~Stub(){cout << "Stub:Destructor" << endl;}};template<typename T>class SmartPtr{private:T* ptr;size_t* pUse;public:SmartPtr(T* p = 0) :ptr(p), pUse(new size_t(1)){}SmartPtr(const SmartPtr& src) : ptr(src.ptr), pUse(src.pUse){++*pUse;}SmartPtr& operator=(const SmartPtr& rhs){++*rhs.pUse;decrUse();ptr = rhs.ptr;pUse = rhs.pUse;return *this;}T* operator->(){if (ptr)return ptr;throw std::runtime_error("access through NULL pointer");}const T* operator->()const{if (ptr)return ptr;throw std::runtime_error("accessthroughNULLpointer");}T& operator*(){if (ptr)return *ptr;throw std::runtime_error("dereferenceofNULLpointer");}const T& operator*()const{if (ptr)return *ptr;throw std::runtime_error("dereferenceofNULLpointer");}~SmartPtr(){decrUse();#ifdef TEST_SMARTPTRstd::cout << "SmartPtr:Destructor" << std::endl;//fortesting#endif}private:void decrUse(){if (--*pUse == 0){delete ptr;delete pUse;}}};int main(){try{SmartPtr<Stub>t();}catch (const exception&err){cout << err.what() << endl;}SmartPtr<Stub>t1(new Stub);SmartPtr<Stub>t2(t1);SmartPtr<Stub>t3(new Stub);t3 = t2;t1->print();(*t3).print();return 0;}
0 0
- 一种智能指针的实现方式
- 智能指针的一种实现
- 智能指针的一种实现
- C++一种智能指针的实现
- c++ 一种智能指针的实现
- 智能指针实现方式
- 一种基于引用计数的智能指针的实现
- 一种基于引用计数机制的智能指针实现
- 一种基于引用计数机制的智能指针实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的实现
- 智能指针的简单实现及两种误用方式
- 智能的实现方式
- 资源共享型智能指针实现方式简述
- (转)智能指针的另外一种实现 - Smart pointers in Delphi
- 软件测试知识点整理
- 黑马程序员——JAVA之面向对象(二)
- 软件测试知识点整理
- ZOJ3646 The Dragon of Loowater
- 【算法】——插入排序(一)
- 一种智能指针的实现方式
- 软件测试知识点整理
- Sql Server 里的向上取整、向下取整、四舍五入取整的实例!
- llvm之clang前端的一些例子:
- 测试的方式
- JavaScript面向对象编程指南(第2版) 笔记
- Convolutional Neural Networks (LeNet)
- App开放接口api安全性—Token签名sign的设计与实现
- [Qt] CFlip 翻页功能实现