c++智能指针简单实现

c++11新特性:智能指针

#ifndef _smart_str
#define _smart_str
#include<iostream>
using namespace std;
class use {//用于测试->重载
public:
	void method(){ cout << "Method is called!" << endl; }
};
template <typename T>
class smart_ptr {
private:
	T* px;
	int* pn;//智能指针最重要的一点:计数
public:
	smart_ptr(T* p) ;//构造函数
	smart_ptr(const smart_ptr<T>& ori);//拷贝构造函数
	smart_ptr<T>& operator=(const smart_ptr<T>& rig);//重载=时注意 返回类型设置时要考虑连续赋值所以不要用void
	~smart_ptr();
	T& operator*()const;//对于指针*,->的实现必不可少
	T* operator->()const;
	void getcount() {
			return *pn;
		}
};
template <typename T>
smart_ptr<T>::smart_ptr(T* p) :px(p)
{
	try
	{
		pn = new int(1);
	}
	catch (const std::exception&)
	{
		delete px;
		px = nullptr;
		delete pn;
		pn = nullptr;
	}
	cout << "Constructor is called!" << endl;
}
template <typename T>
smart_ptr<T>::smart_ptr(const smart_ptr<T>& ori) {
	pn = ori.pn;
	px = ori.px;
	++(*ori.pn);//拷贝赋值计数器加一
	cout << "Copy Constructor is called!" << endl;
}
template <typename T>
smart_ptr<T>& smart_ptr<T>::operator=(const smart_ptr<T>& rig) {
	if (this->px == rig.px)//=赋值注意点1:自我复制处理
	{
		cout << "Self assignment is called!" << endl;
		return *this;
	}
	if (--(*pn) == 0) {//注意店2:要覆盖=左边的值前判断该指针的计数器是否为1,然后释放空间
		delete px;
		px=nullptr;
		delete pn;
		pn=nullptr;
	}
	++(*rig.pn);
	px = rig.px;
	pn = rig.pn;
	cout << "Assignment operator overloaded is called!" << endl;
	return *this;
	
}
template <typename T>
T& smart_ptr<T>::operator*()const {
	cout << "Assignment operator* overloaded is called!" << endl;
	return *px;
}
template <typename T>
T* smart_ptr<T>::operator->()const {
	cout << "Assignment operator-> overloaded is called!" << endl;
	return px;
}
template <typename T>
smart_ptr<T>::~smart_ptr() {
	if (--(*pn) == 0) {
		delete pn;
		delete px;
		px = nullptr;
		pn = nullptr;
		cout << "Destructor is called!" << endl;
	}
	
}
int main() {
	smart_ptr<int> p1(new int(0));
	p1 = p1;
	cout << *p1;
	smart_ptr<int> p2(p1);
	smart_ptr<int> p3(new int(1));
	smart_ptr<use> sp(new use);
	sp->method();
	p3 = p1;
	
	return 0;
}
#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值