智能指针的一种实现

std的auto_ptr实现了接口

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;
}




你可能感兴趣的:(智能指针的一种实现)