C++中智能指针解析

来源:互联网 发布:淘宝角色管理界面 编辑:程序博客网 时间:2024/06/05 04:46

一. 智能指针简介

由于 C++ 语言没有自动内存回收机制,程序员每次 new 出来的内存都要手动 delete。程序员忘记 delete,流程太复杂,最终导致没有 delete,异常导致程序过早退出,没有执行 delete 的情况并不罕见。智能指针是存储指向动态分配(堆)对象指针的类,用于生存期控制,能够确保自动正确的销毁动态分配的对象,防止内存泄露。用智能指针便可以有效缓解这类问题。

boost库中智能指针包括:

boost::scoped_ptr

boost::shared_ptr

boost::scoped_array

boost::shared_array

boost::weak_ptr

boost:: intrusive_ptr

二.每个智能指针的基本用法

1. boost::scoped_ptr:

boost::scoped_ptr是一个比较简单的智能指针,它能保证在离开作用域之后它所管理对象能被自动释放。

#include <iostream>#include <boost/scoped_ptr.hpp>using namespace std;class Book{public:    Book()    {        cout << "Creating book ..." << endl;    }    ~Book()    {        cout << "Destroying book ..." << endl;    }};int main(){       cout << "=====Main Begin=====" << endl;    {        boost::scoped_ptr<Book> myBook(new Book());    }    cout << "===== Main End =====" << endl;    return 0;}

2. boost::shared_ptr

boost::shared_ptr是可以共享所有权的指针。如果有多个shared_ptr共同管理同一个对象时,只有这些shared_ptr全部与该对象脱离关系之后,被管理的对象才会被释放。

#include <iostream>#include <string>#include <boost/shared_ptr.hpp>using namespace std;class Book{private:    string name_;public:    Book(string name) : name_(name)    {        cout << "Creating book " << name_ << " ..." << endl;    }    ~Book()    {        cout << "Destroying book " << name_ << " ..." << endl;    }};int main(){       cout << "=====Main Begin=====" << endl;    {        boost::shared_ptr<Book> myBook(new Book("「1984」"));        cout << "[From myBook] The ref count of book is " << myBook.use_count() << ".\n" << endl;        boost::shared_ptr<Book> myBook1(myBook);        cout << "[From myBook] The ref count of book is " << myBook.use_count() << "." << endl;        cout << "[From myBook1] The ref count of book is " << myBook1.use_count() << ".\n" << endl;        cout << "Reset for 1th time. Begin..." << endl;        myBook.reset();        cout << "[From myBook] The ref count of book is " << myBook.use_count() << "." << endl;        cout << "[From myBook1] The ref count of book is " << myBook1.use_count() << "." << endl;        cout << "Reset for 1th time. End ...\n" << endl;        cout << "Reset for 2th time. Begin ..." << endl;        myBook1.reset();  cout << "===== Main End =====" << endl;    return 0;}

3.boost::shared_array

boost::shared_array类似shared_ptr,它包装了 new[]操作符在堆上分配的动态数组,同样使用引用计数机制为动态数组提供了一个代理,可以在程序的生命周期里长期存在,直到没有任何引用后才释放内存。

#include <boost/smart_ptr.hpp>#include <boost/make_shared.hpp>using namespace boost;using namespace std;int _tmain(int argc, _TCHAR* argv[]){   int *p = new int[100];   shared_array<int> sa(p);   shared_array<int> saEx = sa;   sa[0] = 10;   assert(saEx[0] == 10);   return 0;}

4. boost::weak_ptr

boost::weak_ptr是对对象的一种弱引用,它不会添加对象的引用计数。weak_ptr和shared_ptr之间能够相互转换。shared_ptr能够直接赋值给week_ptr,week_ptr可通过调用lock函数来获得shared_ptr。

class A;class B;typedef shared_ptr<A> A_Share;typedef shared_ptr<B> B_Share;class A{public:        B_Share m_b;};class B{public:        A_Share m_a;};A_Share a(new A());B_Share b(new B());a.m_b = b;b.m_a = a;

5. boost::intrusive_ptr

intrusive_ptr是一个侵入式的引用计数型指针,它对内存占用的要求非常严格,要求必须与原始指针一样,现存代码已经有了引用计数机制管理的对象。

namespace boost {      template<class T> class intrusive_ptr {    public:      intrusive_ptr(T* p,bool add_ref=true);        intrusive_ptr(const intrusive_ptr& r);        ~intrusive_ptr();        T& operator*() const;      T* operator->() const;      T* get() const;       operator unspecified-bool-type() const;     };     template <class T> T* get_pointer(const intrusive_ptr<T>& p);       template <class T,class U> intrusive_ptr<T>    static_pointer_cast(const intrusive_ptr<U>& r);   }  

6. boost::scoped_array

scoped_array 与 scoped_ptr源于相同的设计思想,故而用法非常相似:它只能在被声明的作用域内使用,不能拷贝、赋值。唯一不同的是scoped_array包装的是new[]产生的指针,并在析构时调用delete[],因为它管理的是动态数组,而不是单个动态对象。

#include <iostream>  #include <boost/smart_ptr.hpp>  using namespace std;  using namespace boost;    int main()  {      int *p = new int[10];      scoped_array<int> ps(p);      *ps = 1;            for(int i = 0; i<10;++i)      { cout<<ps[i]<<" ";      }      cout<<endl;      scoped_array<int> ps1;         cot<<ps[i]<<" ";      }      cout<<endl;      scoped_array<int> ps1;       ps1 = ps;                       return 0;  }
原创粉丝点击