一、智能指針
在C++語言編程時,當類中有指針成員時,一般有兩種方式來管理指針成員:一是采用值型的方式管理,每個類對象都保留一份指針指向的對象的拷貝;另一種更優雅的方式是使用智能指針,從而實現指針指向的對象的共享。
智能指針(smartpointer)的一種通用實現技術是使用引用計數(referencecount)。智能指針類將一個計數器與類指向的對象相關聯,引用計數跟蹤該類有多少個對象共享同一指針。
每次創建類的新對象時,初始化指針并將引用計數置為1;當對象作為另一對象的副本而創建時,拷貝構造函數拷貝指針并增加與之相應的引用計數;對一個對象進行賦值時,賦值操作符減少左操作數所指對象的引用計數(如果引用計數為減至0,則刪除對象),并增加右操作數所指對象的引用計數;調用析構函數時,析構函數減少引用計數(如果引用計數減至0,則刪除基礎對象)。
智能指針詳解:
包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost::intrusive_ptr
二、智能指針的一般實現 www.jamo123.com
智能指針通常使用類模板來實現。模擬類指針的各種行為。但是,其最重要的作用是對類指針成員的管理,防止懸垂指針的出現。
template<classT>
classSmartPointer{
public:
SmartPointer(T*t):pt(t){}
T&operator*(){return*pt;}
T*operator->(){returnpt;}
private:
T*pt;
};
三、引用計數的實現
為了實現引用計數,我們定義一個_counter類來記錄引用次數,把_counter類的所有成員設定為private,因為其他的類型并不需要訪問_counter,只有SmartPointer對其進行操作就行了,SmartPointer將設為其友元類。
class_counter{
template<classT>friendclassSmartPointer;
_counter(intu):use(u){}
~_counter(){}
intuse;
};
在SmartPointer類中,保留_counter的指針。
template<classT>
classSmartPointer{
public:
SmartPointer(T*t):pc(new_counter(1)){
cout《"SmartPointer::SmartPointer()invodeduseis:"《pc->use《endl;
this->pt=t;
}
SmartPointer(SmartPointer<T>&rhs){
this->pc=rhs.pc;
this->pt=rhs.pt;
this->pc->use++;
cout《"SmartPointercopyinvokeduseis:"《pc->use《endl;
}
~SmartPointer(){
pc->use--;
cout《"SmartPointer::~SmartPointer()invodeduseis:"《pc->use《endl;
if(pc->use==0)
{
deletept;
deletepc;
}
}
SmartPointer<T>&operator=(SmartPointer<T>rhs){
if(rhs==*this){
return*this;
}
this->pt=rhs.pt;
this->pc=rhs.pc;
this->pc->use++;
cout《"SmartPointer::operator=()invokeduseis:"《pc->use《endl;
return*this;
}
private:
T*pt;
_counter*pc;
};
例如:我們有一個HasPtr類,其類成員中有一個為指針*p.
classHasPtr{
public:
HasPtr(intval):value(val),p(newint(3)){
cout《"HasPtr::HasPtr()invoked"《endl;
}
~HasPtr(){deletep;cout《"HasPtr::~HasPtr()invoded"《endl;}
private:
int*p;
intvalue;
};
如果如下調用:
HasPtr*php=newHasPtr(3);
SmartPointer<HasPtr>psp(php);
SmartPointer<HasPtr>npsp(psp);
我們現在有兩個智能指針對象,指向同一個HasPtr對象,
實現 www.lefeng123.com
_counter的use成員(引用計數)為2.
四、測試
intmain(void)
{
HasPtr*php=newHasPtr(3);
SmartPointer<HasPtr>psp(php);
SmartPointer<HasPtr>npsp(psp);
SmartPointer<HasPtr>nnpsp=npsp;
return0;
}