今天学习了一下智能指针类的使用,想把学习的心得和大家分享一下,在用到智能指针的时候可以查阅和利用!代码如下:
#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;
}