C++代码模拟对象句柄功能
其中类handle就是模拟的句柄类
#pragma once #ifndef HANDLE_H #define HANDLE_H #include<cstdlib> #include<exception> template<typename T> class handle { typedef typename long ptr_ac; public: static ptr_ac* const null_ptr_ac; handle(T* t=NULL):ptr(t),use_p((t==NULL)?null_ptr_ac:(new ptr_ac(1))){} handle(const handle& qih):ptr(qih.ptr),use_p(qih.use_p) {++*use_p;} ~handle(){destory();} handle& operator=(const handle&); T& operator*(); T* operator->(); T& operator*()const; T* operator->()const; private: T* ptr; ptr_ac* use_p; void destory() { if(--*use_p==0) { delete [] ptr; delete [] use_p; } } }; template<typename T> typename handle<typename T>::ptr_ac* const handle<typename T>::null_ptr_ac=new ptr_ac(2); template<typename T> handle<typename T>& handle<typename T>::operator =(const handle& qih) { if(ptr!=qih.ptr) { destory(); ptr=qih.ptr; use_p=qih.use_p; ++*use_p; } return *this; } template<typename T> T& handle<typename T>::operator *() { if(ptr==NULL) throw std::runtime_error("A NULL was dereferenced"); else return *ptr; } template<typename T> T& handle<typename T>::operator *() const { return handle::operator *(); } template<typename T> T* handle<typename T>::operator ->() { if(ptr==NULL) throw std::runtime_error("A NULL used a '->'operator"); else return ptr; } template<typename T> T* handle<typename T>::operator ->() const { return handle::operator ->(); } #endif