通过类来对资源进行管理

来源:互联网 发布:云技术和大数据教程 编辑:程序博客网 时间:2024/04/29 12:25
通过类管理资源分配#include<iostream>using namespace std;template<class T,int sz=1>class PWrap{T* ptr;public:class RangeError{};PWrap(){cout<<"create PW"<<endl;ptr=new T[sz];}~PWrap(){cout<<"xigou"<<endl;delete[] ptr;}T& operator[](int i)throw(RangeError){if(i>0&&i<sz)return ptr[i];throw RangeError();}};class Cat{public:Cat(){cout<<"Cat()"<<endl;}~Cat(){cout<<"~Cat()"<<endl;}void g(){}};class Dog{public :void* operator new[](size_t){cout<<"Allocating a Dog"<<endl;throw 47;}void operator delete[](void*p){cout<<"Deallocating a Dog ";::operator delete[](p);}};class useResources{PWrap<Cat,3>cats;PWrap<Dog>dog;public:useResources(){cout<<"UseResources()"<<endl;}~useResources(){cout<<"~UseResources"<<endl;}void f(){cats[1].g();}};


原创粉丝点击