SmartPointer Smar指针
#include<iostream>
using namespace std;
// private class for use by HasPtr only
class U_Ptr
{
/**
*因为在这个例子中所有的复制都是复制的“变量的常引用”,所以将U_Ptr这个变量的use增加,其他的HasPtr的use也会跟随着改变,
*【目标变量一直就只有一个,所有的复制都只是改变指针而已】
*/
friend class HasPtr;
int *ip;
size_t use;
U_Ptr(int *p): ip(p), use(1) { }
~U_Ptr() { delete ip; }
};
/*** smart pointer class: takes ownership of the dynamically allocated
* object to which it is bound
* User code must dynamically allocate an object to initialize a HasPtr
* and must not delete that object; the HasPtr class will delete it
***/
class HasPtr
{
public:
// HasPtr owns the pointer; pmust have been dynamically allocated
HasPtr(int *p, int i): ptr(new U_Ptr(p)), val(i) { }
// copy members and increment the use count
HasPtr(const HasPtr &orig):
ptr(orig.ptr), val(orig.val) { ++ptr->use; }
HasPtr& operator=(const HasPtr&);
// if use count goes to zero, delete the U_Ptr object
~HasPtr() { if (--ptr->use == 0) delete ptr; }
public:
// copy control and constructors as before
// accessors must change to fetch value from U_Ptr object
int *get_ptr() const { return ptr->ip; }
int get_int() const { return val; }
// change the appropriate data member
void set_ptr(int *p) { ptr->ip = p; }
void set_int(int i) { val = i; }
// return or change the value pointed to, so ok for const objects
// Note: *ptr->ip is equivalent to *(ptr->ip)
int get_ptr_val() const { return *ptr->ip; }
void set_ptr_val(int i) { *ptr->ip = i; }
int get_usecount(){return ptr->use;}
private:
U_Ptr *ptr;
// points to use-counted U_Ptr class
int val;
};
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++rhs.ptr->use; // increment use count on rhs first
if (--ptr->use == 0)
delete ptr; // if use count goes to 0 on this object, delete it
ptr = rhs.ptr; // copy the U_Ptr object
val = rhs.val; // copy the int member
return *this;
}
int main()
{
int obj;cout<<"obj="<<obj<<endl;;
HasPtr ptr1(&obj,0);cout<<"usecount1="<<ptr1.get_usecount()<<endl;
HasPtr ptr2(ptr1);cout<<"usecount1="<<ptr1.get_usecount()<<endl;cout<<"usecount2="<<ptr2.get_usecount()<<endl;
HasPtr ptr3(ptr1);cout<<"usecount1="<<ptr3.get_usecount()<<endl;cout<<"usecount2="<<ptr2.get_usecount()<<endl;
cout<<"int_A:"<<ptr1.get_int()<<" int_B:"<<ptr2.get_int()<<" int_C:"<<ptr3.get_int()<<endl;
ptr1.set_int(9527); // changes val member only in ptr1
cout<<"int_A:"<<ptr1.get_int()<<" int_B:"<<ptr2.get_int()<<" int_C:"<<ptr3.get_int()<<endl;
cout<<"ptr_val_A:"<<ptr1.get_ptr_val()<<" ptr_val_B:"<<ptr2.get_ptr_val()<<" ptr_val_C:"<<ptr3.get_ptr_val()<<endl;
ptr1.set_ptr_val(123); // sets object to which both ptr1 and ptr2 point
cout<<"ptr_val_A:"<<ptr1.get_ptr_val()<<" ptr_val_B:"<<ptr2.get_ptr_val()<<" ptr_val_C:"<<ptr3.get_ptr_val()<<endl;
cout<<"========================================";
}