智能指针类的使用示例

今天学习了一下智能指针类的使用,想把学习的心得和大家分享一下,在用到智能指针的时候可以查阅和利用!代码如下:

#include<iostream>

using namespace std;

class Smart_Ptr{
	friend class Instance_Ptr;
	int *s_p;
	size_t count;
	Smart_Ptr(int *p): s_p(p),count(1) {}
	~Smart_Ptr() {delete s_p;}
};


class Instance_Ptr{
public:
	Instance_Ptr(int *p,int i): ptr(new Smart_Ptr(p)),val(i) {}
	Instance_Ptr(const Instance_Ptr &orig):ptr(orig.ptr),val(orig.val){++ptr->count;}
	Instance_Ptr& operator=(const Instance_Ptr&);
	~Instance_Ptr(){if(--ptr->count==0) delete ptr;}


	int *get_ptr() const {return ptr->s_p;}
	int get_int() const {return val;}
	void set_ptr(int *p) {ptr->s_p=p;}
	void set_int(int i) {val=i;}


	int get_ptr_val() const {return *ptr->s_p;}
	void set_ptr_val(int i) {*ptr->s_p=i;}
private:
	Smart_Ptr *ptr;
	int val;
};


Instance_Ptr& Instance_Ptr::operator=(const Instance_Ptr &rhs)
{
	++rhs.ptr->count;
	if(--ptr->count==0)
		delete ptr;
	ptr=rhs.ptr;
	val=rhs.val;
	return *this;
}
ostream& operator<<(ostream &os, const Instance_Ptr &hp)
{
    os << "*ptr: " << hp.get_ptr_val() << "\t val: " << hp.get_int() << endl;
    return os;
}
int main()
{
    int obj = 0;


    Instance_Ptr ptr1(&obj, 12);
    Instance_Ptr ptr2(ptr1);
    cout << "(1) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl;

    ptr1.set_ptr_val(12); // sets object to which both ptr1 and ptr2 point
    ptr2.get_ptr_val();   // returns 12
    cout << "(2) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl;

    ptr1.set_int(2);   // changes s member only in ptr1
    ptr2.get_int();    // returns 12
    ptr1.get_int();    // returns 0
    cout << "(3) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值