13.27 定义使用引用计数版本的HasPtr
#include<iostream> #include<string> #include<new> using namespace std; class HasPtr { public: HasPtr(const string &s=string()):ps(new string(s)),i(0),use(new size_t(1)) {cout<<"constructer"<<endl;} HasPtr(const HasPtr &h):i(h.i) { cout<<"copy constructer"<<endl; ps=h.ps; ++*h.use; use=h.use; } HasPtr& operator=(const HasPtr &h) { ++*h.use; //将原来分配的内存空间删除 while(--*use==0) { delete ps; delete use; } //指向新的内存空间 ps=h.ps; i=h.i; use=h.use; return *this; } //如果在赋值操作中删除了左边对象的内存空间,则此处调用析构函数时将不再删除内存空间,但是该对象还是会被析构 ~HasPtr() { if(--*use==0) { delete ps; delete use; } cout<<"destructer"<<endl; } private: string *ps; int i; size_t *use; }; int main() { HasPtr h; HasPtr hh(h); hh=h; return 0; }