智能指针的一种实现
2014-04-28 22:28
399 查看
std的auto_ptr实现了接口
T* get() 返回原始指针
void reset() 析构原始指针指向的对象
T* operator ->() 返回原始指针
T& operator *() 返回原始指针指向的对象的引用
T* release() 交还原始指针管理权
基于以上功能要求,实现智能指针如下
测试类
测试代码
T* get() 返回原始指针
void reset() 析构原始指针指向的对象
T* operator ->() 返回原始指针
T& operator *() 返回原始指针指向的对象的引用
T* release() 交还原始指针管理权
基于以上功能要求,实现智能指针如下
#pragma once template<class T> class smart_ptr{ public: //smart_ptr():m_p(0){} smart_ptr(T *p):m_p(p){} ~smart_ptr(); T* get() {return m_p;} void reset(); T* release(); T* operator -> () {return m_p;} T& operator *() {return *m_p;} private: smart_ptr(smart_ptr &); // declare copy constructor and operator = as private to avoid misuse smart_ptr smart_ptr& operator =(smart_ptr&);// T *m_p; }; template<class T> T* smart_ptr<T>::release() { T* temp = m_p; m_p = 0; return temp; } template<class T> void smart_ptr<T>::reset() { if (m_p) { delete m_p; m_p = 0; } } template<class T> smart_ptr<T>::~smart_ptr() { reset(); }
测试类
class testClass { public: testClass(){cout<<"construction testClass"<<endl;} ~testClass(){cout<<"destruction testClass"<<endl;} void print(){cout<<m_str<<endl;} string m_str; };
测试代码
#include <stdio.h> #include <tchar.h> #include <string> #include <ctime> #include <map> #include <iostream> #include <algorithm> #include "header.hpp" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { smart_ptr<testClass> sp1(new testClass); sp1.get()->m_str = "111"; sp1->print(); (*sp1).m_str = "2222"; sp1->print(); //smart_ptr<testClass> sp2 = sp1;//compile error since copy constructor is declared as private testClass *p = sp1.release(); delete p; return 0; }
相关文章推荐
- c++ 一种智能指针的实现
- (转)智能指针的另外一种实现 - Smart pointers in Delphi
- 一种智能指针的实现方式
- 一种基于引用计数机制的智能指针实现
- 智能指针的一种实现
- C++一种智能指针的实现
- 一种基于引用计数机制的智能指针实现
- c++ 智能指针的一种实现方法
- (转)智能指针的另外一种实现 - Smart pointers in Delphi
- 一种基于引用计数的智能指针的实现
- C++中智能指针的工作原理和简单实现
- C++面试题(四)——智能指针的原理和实现
- (C++)智能指针的模拟实现及使用
- Item 45: 利用成员函数模板接受所有兼容类型(智能指针的部分实现)
- Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析(4)
- 智能指针的实现机理
- C++智能指针及其简单实现
- C++智能指针的简单实现
- 动态内存与智能指针及其实现
- C++智能指针及其简单实现