#include<iostream>
using namespace std;
class Point //基礎對象類,要做一個對Point類的智能指針
{
public:
Point(int xVal = 0, int yVal = 0):x(xVal),y(yVal) { }
int getX() const { return x; }
int getY() const { return y; }
void setX(int xVal) { x = xVal; }
void setY(int yVal) { y = yVal; }
private:
int x,y;
};
class RefPtr
{
friend class SmartPtr;
RefPtr(Point *p):ptr(p),count(1){};
~RefPtr(){delete ptr;};
int count;
Point *ptr;
};
class SmartPtr
{
public:
SmartPtr(Point *p):rptr(new RefPtr(p)){cout<<"構造函數"<<endl;};
SmartPtr(const SmartPtr &p); //拷貝構造函數
SmartPtr& operator=(const SmartPtr& rhs); //賦值
~SmartPtr(){
if (rptr->count==0)
delete rptr;
--rptr->count;
};
int getCount()
{
return rptr->count;
}
private:
RefPtr *rptr;
};
SmartPtr::SmartPtr(const SmartPtr &p)
{
cout<<"拷貝構造函數"<<endl;
rptr = p.rptr;
++rptr->count;
}
SmartPtr& SmartPtr::operator=(const SmartPtr& rhs)
{
cout<<"賦值函數"<<endl;
if (this == &rhs)
{
return *this;
}
rptr = rhs.rptr;
++rptr->count;
}
int main()
{
Point *point=new Point(10,10);
SmartPtr *sp1=new SmartPtr(point);
SmartPtr *sp2=new SmartPtr(*sp1);
SmartPtr *sp3=new SmartPtr(*sp2);
SmartPtr *sp4=sp3;
cout<<sp1->getCount()<<endl;
cout<<sp2->getCount()<<endl;
cout<<sp3->getCount()<<endl;
cout<<sp4->getCount()<<endl;
delete sp2;
delete sp3;
cout<<sp1->getCount()<<endl;
return 0;
}
C++ 智能指針
當類中有指針成員時,一般有兩種方式來管理指針成員:一是採用值型的方式管理,每個類對象都保留一份指針指向的對象的拷貝(這些指針分別指向對象的不同拷貝);另一種更優雅的方式是使用智能指針,從而實現指針指向的對象的共享。
智能指針(smart pointer)的一種通用實現技術是使用引用計數(reference count)。智能指針類將一個計數器與類指向的對象相關聯,引用計數跟蹤該類有多少個對象共享同一指針。
每次創建類的新對象時,初始化指針並將引用計數置爲1;當對象作爲另一對象的副本而創建時,拷貝構造函數拷貝指針並增加與之相應的引用計數;對一個對象進行賦值時,賦值操作符減少左操作數所指對象的引用計數(如果引用計數爲減至0,則刪除對象),並增加右操作數所指對象的引用計數;調用析構函數時,構造函數減少引用計數(如果引用計數減至0,則刪除基礎對象)。
實現引用計數有兩種經典策略:一是引入輔助類,二是使用句柄類,下面介紹輔助類:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.