簡介
引用計數指針
幾乎所有稍微複雜點的程序都需要某種形式的引用計數智能指針,這些指針讓我們不再需要爲了管理被兩個或者多個對象共享的對象的生存期而編寫複雜的邏輯,當引用計數將爲零,沒有對象再需要這些共享對象的時候,這個對象就自動銷燬了。
插入式
要求所管理的類提供明確的函數或數據成員用於管理引用計數。
非插入式
對所管理的類沒有任何要求
shared_ptr的成員
namespace boost{
template<typename T> class shared_ptr{
public:
//給定p的所有權,引用計數設爲1
template <class Y> explicit share_ptr(Y *p);
//參數一是資源,參數二負責釋放資源
template<class Y,class D> shared_ptr(Y *p, D d);
~shared_ptr();
//r中保存的資源將與新構造的shared_ptr共享,引用計數加1
shared_ptr(const shared_ptr & r);
//從weak_ptr 構造shared_ptr,如果weak_ptr爲空構造函數會拋出異常 bad_weak_ptr
template<class Y> explicit share_ptr(const weak_ptr<Y> & r);
//從auto_ptr獲取保存的指針的所有權,方法是拷貝一份指針,並調用Release,構造後引用計數爲1,如果不成功拋出:base_alloc
template<cass Y> explicit shared_ptr(const auto_ptr<Y> & r);
shared_ptr& operate=(const shared_ptr &) ;
void reset();
T& operator * () const;
T *operator -> () const;
T *operator get() const;
bool unique() const;
long use_count() const;
operator unspecified_bool_type() const;
void swap(shared_ptr<T> &b);
};
//static_cast 的 shared_ptr版
template<class T, class U>
shared_ptr<T> static_pointer_cast(const shared_ptr<T> &r);
}
shared_ptr和標準容器
typedef std::vector<boost::shared_ptr<A>> container;
typedef contianer::iterator iterator;
container.push_back(boost::shared_ptr<A> p(new A()));
從this創建shared_ptr
有時候,需要從this 獲取shared_ptr,即是說,你希望你的類被shared_ptr管理,你需要把自身轉換爲shared_ptr的方法,解決方案就是boost:weak_ptr
class A;
void do_stuff(boost::shared_ptr<A>p){
}
class A: public boost::enable_shared_from_this<A>{
public:
void call_do_stuff(){
do_stuff(shared_from_this());
}
};
int main(){
boost::shared_ptr<A> p(new A());
p->call_do_stuff();
}