//模拟实现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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 06:32:07