c++智能指针练习

实例如下:
#include <iostream>
using namespace std;

class counter
{

	int m_use;
    template <class T> friend class smartpointer;
    counter(int use):m_use(use){}
    counter(){ m_use = 0;}
};
template <class T>
class smartpointer
{
public:
	smartpointer(T *ptr):m_pt(ptr),m_cnt(new counter(1))
	{
		cout<<"smartpointer::smartpointer() invoked " << m_cnt->m_use++ <<endl;	
	}
	smartpointer(const smartpointer<T>& rhs)
	{
  	    m_pt = rhs.m_pt;
		m_cnt = rhs.m_cnt;
	    ++(m_cnt->m_use);
		cout<<"smartpointer::smartpointer(const smartpointer&) invoked " << m_cnt->m_use++ <<endl;
	}

	~smartpointer()
	{
		cout<<"SmartPointer::~SmartPointer() invoded" << m_cnt->m_use <<endl;
		if(--(m_cnt->m_use) == 0)
		{
			delete m_pt;
			delete m_cnt;
		}
	}
	
	smartpointer& operator=(const smartpointer& rhs)
	{
		if(rhs == *this)
			return *this;
		
		m_pt = rhs.m_pt;
		m_cnt = rhs.m_cnt;
		++(m_cnt->m_use);
		cout<<"SmartPointer::operator=SmartPointer() invoded" << m_cnt->m_use <<endl;
		return *this;
	}
private:
	T *m_pt;
	counter *m_cnt;
};

class test
{
private:
	int t;
	int *value;
public:
	test(int v):t(v), value(& v)
	{
		cout << t <<endl;
	}
	~test()
	{
		delete value;
		cout << "test::~test() invoked" <<endl;
	}
};

int main(int argc, char *argv[])
{
	test *t = new test(10);
	smartpointer<test> pp(t);
	smartpointer<test> pp2(pp);
	smartpointer<test> pp3 = pp2;
	
    return 0;
}


	

	

写的不太标准,主要参考c++ primer中的讲解
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值