C++智能指針shared_array

        這幾天寫一個程序,經常用到動態分配的指針,然後自己又有強迫症,每次動態分配之後,不delete或者delete[]掉,就不舒服,但是同時自己又有健忘症,有時候寫着寫着,又忘了delete或者delete[]了,想起來前段時間瞭解到的智能指針,可以在變量生存週期結束後,自動釋放內存,這讓我甚是歡喜,何不來試試?但是畢竟是初次使用,所以還是先做了一些程序測試,避免後面出bug。因爲主要用到的是動態分配的數組,所以本文主要介紹shared_array。比較詳細和總體的介紹,大家可以參考http://blog.csdn.net/xt_xiaotian/article/details/5714477
       首先介紹一下這個智能指針從哪裏來,首先,memory頭文件在表示智能指針的std命名空間中定義瞭如下類型(截圖來自VC++2012入門經典):
       
        當然,其實仔細看一下,裏面還有幾種其他類型的智能指針定義,也就不一一說了,這裏不是重點。
        上面這些智能指針類型都是定義在std命名空間中的,實際上,除了std之外,有一個類似的,甚至更加強大的模板庫boost,這個庫需要自己去下載和配置,具體去sourceforge上搜索下載最新版即可(http://sourceforge.net/projects/boost/?source=directory),到我寫這個博客的時候,最新版是1.59,我boost_1_59_0.zip,並解壓後,直接將boost_1_59_0文件夾下的boost文件夾複製到VS的安裝目錄的VC\include文件夾下即可,如下圖:
       
        然後在使用boost中定義的智能指針時,只要包含頭文件#include <boost\smart_ptr.hpp>,再加上using namespace boost就可以使用了。
                  
        上圖截自boost庫關於Smart Pointers的說明文檔(http://www.boost.org/doc/libs/1_59_0/libs/smart_ptr/smart_ptr.htm),也就是定義了六中智能指針,有興趣的自己去學習下,本文還是隻講一下shared_array了。
        shared_array的類摘要如下:         
namespace boost {
  template<class T> class shared_array {
    public:
      typedef T element_type;
      explicit shared_array(T * p = 0);
      template<class D> shared_array(T * p, D d);
      ~shared_array(); // never throws
      shared_array(shared_array const & r); // never throws
      shared_array & operator=(shared_array const & r); // never throws
      void reset(T * p = 0);
      template<class D> void reset(T * p, D d);
      T & operator[](std::ptrdiff_t i) const; // never throws
      T * get() const; // never throws
      bool unique() const; // never throws
      long use_count() const; // never throws
      operator unspecified-bool-type() const; // never throws
      void swap(shared_array<T> & b); // never throws
  };
  template<class T>
    bool operator==(shared_array<T> const & a, shared_array<T> const & b); // never throws
  template<class T>
    bool operator!=(shared_array<T> const & a, shared_array<T> const & b); // never throws
  template<class T>
    bool operator<(shared_array<T> const & a, shared_array<T> const & b); // never throws
  template<class T> void swap(shared_array<T> & a, shared_array<T> & b); // never throws
}
        好了,下面直接就上測試代碼吧,爲了簡單,我用了int類型的動態數組,當然,也可以換成其他的數據類型或者類,不然這個就太侷限了。。
#include <iostream>
#include <boost\smart_ptr.hpp>
using namespace std;
using namespace boost;

int main()
{
	int *int_array = new int[10];// 動態分配一個數組
	for (int i = 0; i < 10; i++) {
		int_array[i] = i + 1;
	}
	shared_array<int> smart_int_array(int_array);// 將數組定義位智能指針

	// 不同的引用數組方式
	cout << "訪問方式1:通過原始數組名來訪問" << endl;
	for (int i = 0; i < 10; i++) {
		cout << int_array[i] << " ";
	}
	cout << endl;
	cout << "訪問方式1:通過智能指針訪問" << endl;
	for (int i = 0; i < 10; i++) {
		cout << smart_int_array[i] << " ";
	}	
	cout << endl;

	// 另外一種定義智能指針的方法,也就是先定義,後賦值的方法
	// 測試結果證明也是可行的
	shared_array<int> smart_int_array2;
	// 下面要注意了,在初始化的時候,不能再用int_array作爲形參了
	// 也沒仔細分析原因,最後程序會出現崩潰,也就是說,同一個數組
	// 只能用一個智能指針來管理吧
	smart_int_array2 = shared_array<int>(new int[10]);

	for (int i = 0; i < 10; i++) {
		smart_int_array2[i] = 11 + i;
	}
	cout << "先定義,再初始化,再賦值的方式" << endl;
	for (int i = 0; i < 10; i++) {
		cout << smart_int_array2[i] << " ";
	}
	cout << endl;

	// // 再有就是最有意思的了 ///////////////////////
	// 我先定義一個數組
	int *int_array2 = new int[10];// 動態分配一個數組
	for (int i = 0; i < 10; i++) {
		int_array2[i] = i + 21;
	}
	// 下面驗證發現輸出的值沒有問題
	cout << endl << "定義智能指針前數組的值:" << endl;
	for (int i = 0; i < 10; i++) {
		cout << int_array2[i] << " ";
	}
	cout << endl;
	// 我再在一個局部作用域內爲該數組指定一個智能指針
	if (true) {
		shared_array<int> smart_int_array3(int_array2);
	}
	// 當出了這個作用域,智能指針被銷燬,我們再來看下原始數組變了沒
	cout << "智能指針銷燬後數組的值:" << endl;
	for (int i = 0; i < 10; i++) {
		cout << int_array2[i] << " ";
	}
	cout << endl;

	return 1;
}
        程序輸出結果如下圖:
 
        尤其是最後一個部分,我是覺得很神奇的,說明不管你原始數組定義的作用域在哪裏,只要在其上定義的智能指針別銷燬了,那麼,這部分空間也就被銷燬了,那麼再輸出的話,看到的都是一些無效值了,在使用中還是要注意的。
        另外,關於定義方式,還是比較好的,定義時不需要馬上初始化和賦值,再加上數組的[]訪問操作符仍然存在,最後還不需要我們手動delete[],真是再好不過了。
        還有補充一點,就是這種shared_array是可以用=對其中的元素逐個賦值的,不像scoped_array和scoped_ptr,詳細內容,大家查看文檔便知,網址文中也有。
        (說的不對的,望指正,謝謝!)

發佈了27 篇原創文章 · 獲贊 70 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章