【c++】模拟实现boost库里的scoped_ptr

来源:互联网 发布:文件加密解密算法 编辑:程序博客网 时间:2024/05/22 10:50
//模拟实现boost下的scoped_ptr#include <iostream>#include <assert.h>using namespace std;template <class T>class scoped_ptr{private:T * px;scoped_ptr(scoped_ptr const &);scoped_ptr& operator=(scoped_ptr const &);void operator==(scoped_ptr const &)const;void operator!=(scoped_ptr const &)const;public:scoped_ptr(T *p = 0) :px(p){}//从auto_ptr获得指针的管理权scoped_ptr(std::auto_ptr<T> p) :px(p.release()){}~scoped_ptr(){delete px;}// 删除原来的指针,保存新的指针void reset(T * p = 0){assert(p == 0 || p != px);scoped_ptr<T>(p).swap(*this);}T& operator*()const{assert(px != 0);return *px;}T* operator->()const{assert(px != 0);return px;}T* get()const{return px;}void swap(scoped_ptr & b){T *tmp = b.px;b.px = px;px = tmp;}};int main(){int *p = new int(10);scoped_ptr<int> ptr(p);cout << *ptr << endl;return 0;}

0 0