---
title: "智能指针的简易实现"
author: "vearne"
date: "2012-07-12T16:26:52Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-07-12T16:31:38Z"
id: 1586752
url: "https://vearne.iteye.com/blog/1586752"
---

```
#include <iostream>
using namespace std;
class smart_count{
private:
	int use_count;
public:
	smart_count(int c=0):use_count(c){
	
	}
	~smart_count(){}
	int addref(){
		return ++use_count;
	}
	int release(){
		return --use_count;
	}
};
template<class T>
class smart_ptr{
private:
	T* p;
	smart_count* u;
public:
	smart_ptr(T* tp):p(tp),u(new smart_count(1)){
	}
	smart_ptr():p(NULL),u(NULL){}
	~smart_ptr(){
		if(p&&u->release()<=0){
			delete p;
			delete u;
			p = NULL;
		}
	}
	smart_ptr(smart_ptr<T>& sp){
		p = sp.p;
		u = sp.u;
		if(u){
			u->addref();
		}
	}
	smart_ptr<T>& operator=(smart_ptr<T>& t){
		if(p&&u->release()<=0){
			delete p;
			delete u;
		}
		p = t.p;
		u = t.u;
		if(u){
			u->addref();
		}
	}
	T* operator->(){//这段代码让我困惑，这样就能调用p的函数了?
		return p;
	} 
	T& operator*(){
		return *p;
	}
	T* get(){
		return p;
	}
	void reset(T* t){
		if(p&&u->release()<=0){
			delete p;
			delete u;
		}
		p = t;
		if(p){
			u = new smart_count(1);
		}else{
			u = NULL;
		}
	
	}
	
};
class Car{
private:
	int data;
public:
	Car(int d):data(d){
		cout<<"constructor car"<<endl;
	}
	~Car(){
		cout<<"destructor car"<<endl;
	}
	void f(int a=0){
		cout<<"ok = "<<a+data<<endl;
	}
};
int main(){
	Car* cp = new Car(1);
	smart_ptr<Car> sp(cp);
	sp->f(2);
	(*sp).f(2);

}
```