C++智能指標,指標容器原理及簡單實現(auto_ptr,scoped_ptr,ptr_vector).

來源:互聯網
上載者:User

標籤:except   tmp   The   print   typename   ant   拷貝建構函式   pen   智能指標   

目錄

  • C++智能指標,指標容器原理及簡單實現(auto_ptr,scoped_ptr,ptr_vector).
  • auto_ptr
  • scoped_ptr
  • ptr_vector
C++智能指標,指標容器原理及簡單實現(auto_ptr,scoped_ptr,ptr_vector).前言

最近再寫一個muduo的非同步日誌接觸了很多智能指標,但是又不打算用boost庫,只好模一個來用用了.

智能指標的本質即用棧上對象來管理堆上資料的生命週期.

智能指標本身是一個對象,它在棧上建立,構造的時候分配堆上資源,析構的時候釋放資源,這樣就避免了堆上資料資源流失的情況.
同時重載它的-> 和 * 運算子實現如同裸指標一樣的操作.

下面看看幾個局部智能指標對象的實現代碼。

auto_ptr

auto_ptr特點: 實現拷貝建構函式, 重載 = 運算子, 實現->、* 運算子, 使它能夠像普通指標一樣 使用,
同時通過release() 和 reset() 方法實現安全的轉移使用權 .

#ifndef _AUTO_PTR_HH#define _AUTO_PTR_HHtemplate<typename T>class auto_ptr{public:    explicit auto_ptr(T* p = 0):m_ptr(p){printf("1\n");    }        auto_ptr(auto_ptr& obj):m_ptr(obj.release()){printf("2\n");    }        auto_ptr& operator=(auto_ptr& obj){printf("3\n");        reset(obj.release());        return *this;    }        ~auto_ptr(){printf("4\n");        delete m_ptr;    }    T* release(){        T* tmp = m_ptr;        m_ptr = 0;        return tmp;    }        void reset(T* p){        if(m_ptr != p)            delete m_ptr;        m_ptr = p;    }        T* get() const {        return m_ptr;    }        T* operator->(){        return get();    }        T& operator*(){        return *get();    }    private:    T* m_ptr;};#endif

測試代碼:

#include "ScopePtr.hh"#include "auto_ptr.hh"#include <stdio.h>class NonCopyable{protected: //建構函式可以被衍生類別調用,但不能直接構造對象    NonCopyable() {printf("Nocopy Constroctr\n");}    ~NonCopyable() {printf("~Nocopy DeConstroctr\n");}private:    NonCopyable(const NonCopyable &);    const NonCopyable &operator=(const NonCopyable &);};class Test// : private NonCopyable{{public:    Test(){printf("Constroctr\n");}    ~Test(){printf("~DeConstroctr\n");}};int main(){        //scoped_ptr<Test> st(new Test);        auto_ptr<Test> ap1(new Test);    auto_ptr<Test> ap2(new Test);    auto_ptr<Test> ap3(ap2);        ap2 = ap3;        getchar();    return 0;}
Constroctr1Constroctr12344~DeConstroctr4~DeConstroctr
scoped_ptr

這個是boost庫裡面的東西,它和auto_ptr正相反: 將拷貝構造和=重載 都配置為私人,已達到不允許轉移擁有權的目的.

#ifndef _SCOPE_PTR_HH#define _SCOPE_PTR_HH//  scoped_ptr mimics a built-in pointer except that it guarantees deletion//  of the object pointed to, either on destruction of the scoped_ptr or via//  an explicit reset(). scoped_ptr is a simple solution for simple needs;//  use shared_ptr or std::auto_ptr if your needs are more complex./*scoped_ptr 是局部智能指標 不允許轉讓所有權。*/template <class T>class scoped_ptr{public:    scoped_ptr(T *p = 0) :m_ptr(p) {    }        ~scoped_ptr(){        delete m_ptr;    }        T&operator*() const {        return *m_ptr;    }        T*operator->() const {        return m_ptr;    }        void reset(T *p)//擁有權不允許轉讓  但是可以讓智能指標指向另一個空間      {        if (p != m_ptr && m_ptr != 0)            delete m_ptr;        m_ptr = p;    }    T* get(){        return m_ptr;    }private://將拷貝構造和賦值  以及判等判不等  都設定為私人方法    //對象不再能調用,即不能拷貝構造和賦值  也就達到了不讓轉移擁有權的目的    scoped_ptr(const scoped_ptr<T> &y);    scoped_ptr<T> operator=(const scoped_ptr<T> &);    void operator==(scoped_ptr<T> const &) const;    void operator!=(scoped_ptr<T> const &) const;    T* m_ptr;};#endif
ptr_vector

這個也是boost裡面的東西,如果我們光放對象指標到vector裡面,容器析構的時候雖然會析構自己開闢出來的存放指標的空間,但不會析構指標本身指向的空間,於是有了這個容器.

#ifndef _PTR_VECTOR_HH#define _PTR_VECTOR_HH#include "auto_ptr.hh"#include <vector>template<typename T>class ptr_vector : public std::vector<T*>{public:    ~ptr_vector(){        clear();    }    void clear(){        typename std::vector<T*>::iterator it;        for(it = std::vector<T*>::begin(); it != std::vector<T*>::end(); ++it){            delete *it;//釋放指標指向的記憶體.        }                /*        for(size_t i = 0; i < std::vector<T*>::size(); ++i){            delete std::vector<T*>::back();        }*/                std::vector<T*>::clear(); //釋放指標本身.    }    typename std::vector<T*>::iterator erase(typename std::vector<T*>::iterator it){        if(it >= std::vector<T*>::begin() && it < std::vector<T*>::end()){            delete *it;            std::vector<T*>::erase(it);        }    }    void pop_back(){        if(std::vector<T*>::size() > 0){            delete std::vector<T*>::back();            std::vector<T*>::pop_back();        }    }        void push_back(T* const &v){        auto_ptr<T> ap(v);        std::vector<T*>::push_back(v);        ap.release();    }    void push_back(auto_ptr<T> &v){        std::vector<T*>::push_back(v.get());        v.release();    }    };#endif

測試代碼:

class Test// : private NonCopyable{{public:    Test(int a = 99):a(a){printf("Constroctr\n");}    ~Test(){printf("~DeConstroctr\n");}    int get(){return a;}private:    int a;};int main(){    auto_ptr<Test> ap1(new Test(0));    auto_ptr<Test> ap2(new Test(1));    auto_ptr<Test> ap3(new Test(2));    printf("%d\n", ap1->get());        ptr_vector<Test> apv;    apv.push_back(ap1);    apv.push_back(ap2);    apv.push_back(ap3);    printf("%d %lu \n", apv.front()->get(),apv.size());/*    apv.pop_back();    printf("%lu\n", apv.size());    apv.pop_back();    printf("%lu\n", apv.size());        apv.pop_back();    printf("%lu\n", apv.size());*/    apv.pop_back();    printf("%lu\n", apv.size());            ptr_vector<Test>::iterator it = apv.begin();    apv.erase(it);    printf("%lu\n", apv.size());        getchar();                return 0;}
ConstroctrConstroctrConstroctr00 3 ~DeConstroctr2~DeConstroctr1~DeConstroctr

本文主介紹了智能指標的本質,及兩種簡單的智能指標實現與一個指標容器的實現.

事實上現在auto_ptr用的不多,如果沒對原來傳進來的指標進行處理,轉移後,原來的指標為空白了,如果有人去使用既會造成問題。
vector也存在很多問題,pop_back()一個空的容器,vector裡面照樣會做--size,這時候容器大小從0就變成了無限大,後果無法預料,.本例中對這種情況進行了處理. pop_back()一個空的vector將什麼都不做. 但是vector用法還是有講究的,不然容易造成問題.

C++智能指標,指標容器原理及簡單實現(auto_ptr,scoped_ptr,ptr_vector).

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.