【c++】模拟实现boost库里的scoped_ptr
2015-07-17 11:28
465 查看
//模拟实现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; }
相关文章推荐
- [C++] Excel文件读写
- C++中的构造函数的用法
- C语言程序的内存如何布局
- VC++ 2008 Express Edition 带资源编辑器
- c++builder 6.0 将DBGrid中的数据导出到Word和Excel
- C++中两种创建对象的方法
- c++ 输入输出流
- c语言 如何判断是不是 可显字符
- [leetcode-238]Product of Array Except Self(C语言)
- C/C++头文件一览
- C++将string转化成字符串数组
- 计数排序、基数排序、桶排序
- C++中,结构体与类的 sizeof 大小
- c++组合 聚合 关联 依赖
- C++11/14 lamba, 仿函数 对比
- c++ 虚函数与纯虚函数的区别(深入分析)
- 深入理解C++的多态性
- C++重载输出操作符
- 浅谈C++多态性
- CodeForces 548C