weak_ptr和intrusive_ptr

1、weak_ptr

創(chuàng)新互聯公司專注于企業(yè)全網整合營銷推廣、網站重做改版、莒南網站定制設計、自適應品牌網站建設、H5頁面制作成都商城網站開發(fā)、集團公司官網建設、成都外貿網站制作、高端網站制作、響應式網頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為莒南等各大城市提供網站開發(fā)制作服務。

  (1)、weak_ptr是為了配合shared_ptr而引入的智能指針,它更像是shared_ptr的一個助手,它不具有普通指針的行為,

沒有重載operator*和->,它的最大作用在于協(xié)助shared_ptr工作,像旁觀者那樣觀測資源的使用情況。

  (2)、2個重要接口:bool expired()const ;// 判斷是否過期

  lock()函數是弱指針的核心;

  (3)、獲得資源的觀測權,但weak_ptr沒有共享資源,它的構造不會引起引用計數的增加,它的析構也不會導致引用計數減少,

它只是一個靜靜的觀察者。

2、使用weak_ptr

  調用系統(tǒng)庫的:

#include<iostream>
#include<boost/smart_ptr.hpp>
using namespace std;
using namespace boost;

int main(void){
    int *p = new int(10);
    shared_ptr<int> sp(p);
    
    weak_ptr<int> wp(sp);//1、本身對wp的創(chuàng)建與析構是不會增加/減少use_count;
    cout<<wp.use_count()<<endl;//2、顯示的是它所觀測對象的引用計數器

    if(!wp.expired()){  //沒過期(use_count != 0,空間還沒釋放)
        shared_ptr<int> sp1 = wp.lock();
        //3、wp的lock()函數在有效的前提下可以構造對象(構造的是所觀測的對象)。
        //使use_count加1;
    }//失效的話,構建的是一個空對象,引用計數將不會在增加?。?!

}

 3、weak_ptr源碼剖析

  結合shared_ptr和前面的所有,刪除器,shared_array、weak_ptr給出模擬的部分代碼:

  模仿源代碼,寫出了最重要的函數:

#ifndef _CONFIG_H_
#define _CONFIG_H_

#include<iostream>
using namespace std;

//#define DISPLAY

#endif
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef _SHARED_PTR_H_
#define _SHARED_PTR_H_

#include"shared_count.h"

template<class T>
class weak_ptr;

template<class T>
class shared_ptr{
    friend class weak_ptr<T>;
    typedef shared_ptr<T> this_type;
public:
    template<class Y, class D>
        shared_ptr(Y *p, D d) : px(p), pn(p, d){}//支持傳遞刪除器
    shared_ptr(T *p = 0) : px(p), pn(p){
#ifdef DISPLAY
        cout<<"Create shared_ptr object!"<<endl;
#endif
    }
    shared_ptr(shared_ptr<T> const &r) : px(r.px), pn(r.pn){}
    shared_ptr<T>& operator=(shared_ptr<T> const &r){
        if(this != &r){
            this_type(r).swap(*this);//調用拷貝構造,先創(chuàng)建一個無名臨時的對象
        }
        return *this;
    }
    ~shared_ptr(){
#ifdef DISPLAY
        cout<<"Free shared_ptr object"<<endl;
#endif
    }
public:
    T& operator*()const{
        return *(get());
    }
    T* operator->()const{
        return get();
    }
    T* get()const{
        return px;
    }
public:
    long use_count()const{
        return pn.use_count();
    }
    bool unique()const{
        return pn.unique();
    }
    void reset(T *p){
        this_type(p).swap(*this);
    }
    void swap(shared_ptr<T> &other){
        std::swap(px, other.px); //指針的交換
        pn.swap(other.pn);
    }
public:
    template<class Y>
    shared_ptr(weak_ptr<Y> const &r) : pn(r.pn){
        px = r.px;
    }

private:
    T *px;
    shared_count pn;
};

#endif
/////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _SHARED_COUNT_H_
#define _SHARED_COUNT_H_

#include"config.h"
#include"sp_counted_base.h"
#include"sp_counted_impl_xx.h"


class shared_count{
    friend class weak_count;
public:
    template<class T>  //此時類型不定,寫模板函數
        shared_count(T *p) : pi(new sp_counted_impl_xx<T>(p)){
#ifdef DISPLAY
        cout<<"Create shared_cout object!"<<endl;
#endif
    }
    template<class Y, class D>
    shared_count(Y *p, D d) : pi(0){
        typedef Y* P;
        pi = new sp_counted_impl_pd<P, D>(p, d);
    }
    shared_count(shared_count const &r) : pi(r.pi){
        if(pi){
            pi->add_ref_copy();
        }
    }
    ~shared_count(){
#ifdef DISPLAY
        cout<<"Free shared_count object"<<endl;
#endif
        if(pi){
            pi->release();
        }
    }
public:
    long use_count()const{
        return pi != 0 ? pi->use_count() : 0;
    }
    bool unique()const{
        return use_count() == 1;
    }
    void swap(shared_count &r){
        sp_counted_base *tmp = r.pi;
        r.pi = pi;
        pi = tmp;
    }
public:
    explicit shared_count(weak_count const &r);
private:
    sp_counted_base *pi;
};
/////////////////////////////////////////////////////
template<class P, class D>
class sp_counted_impl_pd : public sp_counted_base{
public:
    sp_counted_impl_pd(P p, D d) : ptr(p), del(d){}
public:
    void dispose(){
        del(ptr);
    }
private:
    P ptr;
    D del;
};
/////////////////////////////////////////////////////////////////////
class weak_count{
    friend class shared_count;
public:
    weak_count(shared_count const &r) : pi(r.pi){
        if(pi != 0){
            pi->weak_add_ref();
        }
    }
    ~weak_count(){
        if(pi){
            pi->weak_release();
        }
    }
public:
    long use_count()const{
        return pi != 0 ? pi->use_count() : 0;
    }
private:
    sp_counted_base *pi;
};

shared_count::shared_count(weak_count const &r) : pi(r.pi){
    if(pi){
        pi->add_ref_lock();
    }
}
#endif
//////////////////////////////////////////////////////////////////////////////
#ifndef SP_COUNTED_BASE_H_
#define SP_COUNTED_BASE_H_

#include"config.h"

class sp_counted_base{  //抽象類
public:
    sp_counted_base() : use_count_(1), weak_count_(1){
#ifdef DISPLAY
        cout<<"Create sp_counted_base object"<<endl;
#endif
    }
    virtual ~sp_counted_base(){
#ifdef DISPLAY
        cout<<"Free sp_counted_base object"<<endl;
#endif
    }
public:
    virtual void dispose() = 0; //純虛函數
    void release(){
        if(--use_count_ == 0){
            dispose();
            delete this;
        }    
    }
public:
    long use_count()const{
        return use_count_;
    }
    void add_ref_copy(){
        ++use_count_;
    }
    void weak_add_ref(){
        ++weak_count_;
    }
    virtual void destroy(){
        delete this;
    }
    void weak_release(){
        if(--weak_count_ == 0){
            destroy();
        }
    }
    bool add_ref_lock(){
        if(use_count == 0){
            return false;
        }
        ++use_count_;
        return true;
    }
private:
    long use_count_;
    long weak_count_;
};

#endif
/////////////////////////////////////////////////////////////////////////////////
#ifndef _SHARED_ARRAY_H_
#define _SHARED_ARRAY_H_

#include"checked_delete.h"

template<class T>
class shared_array{
public:
    typedef checked_array_deleter<T> deleter;
    shared_array(T *p = 0) : px(p), pn(p, deleter()){} //無名對象
    ~shared_array(){
        
    }
public:
    T& operator[](int i)const{
        return px[i];
    }
private:
    T *px;
    shared_count pn;  //必須用到引用計數器對象
};

#endif
////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _CHECKED_DELETE_H_
#define _CHECKED_DELETE_H_

template<class T>
void checked_array_delete(T *x){
    delete []x;
}

template<class T>
struct checked_array_deleter{
public:
    void operator()(T *x)const{
        checked_array_delete(x);        
    }
};

#endif
//////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _WEAK_PTR_H_
#define _WEAK_PTR_H_

#include"shared_ptr.h"

template<class T>
class shared_ptr;

class shared_count;
template<class T>
class weak_ptr{
    friend class shared_ptr<T>;
    friend class shared_count;
public:
    template<class Y>
    weak_ptr(shared_ptr<Y> const &r) : px(r.px), pn(r.pn){}
    ~weak_ptr(){}
public:
    long use_count()const{
        pn.use_count();
    }
    bool expired()const{
        return pn.use_count() == 0;
    }
    shared_ptr<T> lock()const{
        return shared_ptr<T>(*this);
    }
private:
    T *px;
    weak_count pn;
};

#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef SP_COUNTED_IMPL_XX_H_
#define SP_COUNTED_IMPL_XX_H_

#include"sp_counted_base.h"

template<class T>
class sp_counted_impl_xx : public sp_counted_base{
public:
    sp_counted_impl_xx(T *p) : px_(p){
#ifdef DISPLAY
        cout<<"Create sp_counted_impl_xx object"<<endl;
#endif
    }
    ~sp_counted_impl_xx(){
#ifdef DISPLAY
        cout<<"Free sp_counted_impl_xx object"<<endl;
#endif
    }
public:
    void dispose(){
        delete px_;
    }
private:
    T *px_;
};

#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////
#include<iostream>
#include"shared_ptr.h"
#include"shared_array.h"
#include"weak_ptr.h"
using namespace std;

int main(void){
    int *p = new int(10);

    shared_ptr<int> sp(p);
    weak_ptr<int> wp(sp);
    if(!wp.expired()){
        shared_ptr<int> sp1 = wp.lock();//返回真實的對象
        cout<<sp.use_count()<<endl;
    }
    cout<<sp.use_count()<<endl;

}

這是這個智能指針的最主要的剖析,關鍵理清脈絡,條理清晰一些,就可以分析出來!

4、intrusive_ptr的使用

  適用情景:(1)、對內存的占用要求非常嚴格,不能有引用計數的內存開銷;

  (2)、這時的代碼中已經有了引用計數機制管理的對象;

重點掌握如何使用:

  (1)、兩個方法必須重寫(增加/減少引用計數)

  (2)、必須自己編寫管理引用計數的類

  (3)、要封裝到一個類中,在繼承(把自己的類侵入到智能指針中進行管理)

具體使用的一個類子如下:

#include<iostream>
#include<boost/smart_ptr.hpp>
using namespace std;
using namespace boost;
 
//1、實現2個重要的函數
template<class T>
void intrusive_ptr_add_ref(T *t){ //增加引用計數
    t->add_ref_copy();
}
template<class T>
void intrusive_ptr_release(T *t){  //減少引用計數
    t->release();
}

//2、提供管理對象
class Counter{
public:
    Counter() : use_count_(0){
    
    }
    ~Counter(){
    
    }
public:
    void add_ref_copy(){
        ++use_count_;
    }
    void release(){
        if(--use_count_ == 0){
            delete this;
        }
    }
private:
    long use_count_;
};
//3、定義自己的對象
class Test;
ostream& operator<<(ostream &out, const Test &t);
class Test : public Counter{
    friend     ostream& operator<<(ostream &out, const Test &t);
public:
    Test(int d = 0) : data(d){}
    ~Test(){}
private:
    int data;
};

ostream& operator<<(ostream &out, const Test &t){
    out<<t.data;
    return out;
}

int main(void){
    Test *pt = new Test(10);
    intrusive_ptr<Test> ip(pt);
    cout<<*ip<<endl;

}

結果如下:

weak_ptr和intrusive_ptr

新聞名稱:weak_ptr和intrusive_ptr
轉載源于:http://www.muchs.cn/article40/jpjeho.html

成都網站建設公司_創(chuàng)新互聯,為您提供網站制作、營銷型網站建設微信小程序、外貿網站建設、、網站排名

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

外貿網站制作