#include <iostream>#include <string>#include <conio.h> //1.範圍指標//它獨佔一個動態分配的對象,對應的類名為boost::scoped_ptr,定義在boost/scoped_ptr.hpp中。不像std::auto_ptr,範圍指標不能傳遞它所包含的對象的所有權到另一個範圍指標。一旦用一個地址來初始化,這個動態分配的對象將在析構階段釋放。因為一個範圍指標只是簡單儲存和獨佔一個記憶體位址,所以boost::scoped_ptr的實現就要比std::auto_ptr簡單。在不需要所有權傳遞的時候應該優先使用boost::scoped_ptr.在這些情況下,比起std::auto_ptr它是一個更好的選擇,因為可以避免不經意間的所有權傳遞。因此我們通常可以用它來實現局部動態對象的自動釋放,比如在函數調用中產生的動態對象。#include <boost/scoped_ptr.hpp>void test1(){boost::scoped_ptr<int> p(new int);*p=1; *p.get()=2;p.reset(new int);}//2.範圍數組//範圍數組的使用方式與範圍指標相似。關鍵不同在於,範圍數組的解構函式使用delete[]操作符來釋放所包含的對象。因為該操作符只能用於數組對象,所以範圍數組必須通過動態分配數組來初始化。對應的範圍數組類名為boost::scoped_array,它的定義在boost/scoped_array.hpp裡。#include <boost/scoped_array.hpp>void test2(){boost::scoped_array<int> ap(new int[2]);*ap.get()=1;ap[1]=2;ap.reset(new int[3]);}//3.共用指標//這個智能指標命名為boost::shared_ptr,定義子啊boost/shared_ptr.hpp裡。智能指標boost::shared_ptr基本上類似於boost_scoped_ptr.關鍵不同之處在於boost::shared_ptr類型的智能指標共用所有權。子啊這種情況下,當引用對象的最後一個智能指標銷毀後,對象才會釋放。因為所有權可以在boost::shared_ptr之間共用,任何一個共用指標都可以被複製,這跟boost::scoped_ptr是不同的。這樣就可以在標準容器裡儲存智能指標了——你不能再標準容器中儲存std::suto_ptr,因為他們在拷貝的時候傳遞了所有權。#include <vector>#include <algorithm>#include <boost/shared_ptr.hpp>void myprint(boost::shared_ptr<int> i){printf("%d\n",*i);}void test3(){std::vector<boost::shared_ptr<int>>v;boost::shared_ptr<int> s1(new int(1));boost::shared_ptr<int> s2(new int(2));v.push_back(s1);v.push_back(s2);std::for_each(v.begin(),v.end(),myprint);//輸出 1 2}#include <stdio.h>#include <stdlib.h>class Test{public:Test(int i):_i(i){printf("test construct:%d\n",_i);}~Test(){printf("~test destroyed:%d\n",_i);}void myprint(){printf("test value:%d\n",_i);}private:int _i;};void test4(){boost::shared_ptr<Test> te1(new Test(1));//test construct:1boost::shared_ptr<Test> te2(te1);boost::shared_ptr<Test> te3(te1);te1.reset(new Test(2));//test construct:2te1->myprint();//test value:2te2->myprint();//test value:1te3->myprint();//test value:1//最後輸出//~test destroyed:1//~test destroyed:2} //4.共用數組//共用數組的行為類似於共用指標。關鍵不同在於共用數組在析構是,預設使用的是delete[]操作符來釋放所包含對象。因為這個操作符只能用於數組對象,共用數組必須通過動態分配的數組地址來初始化。共用數組對應的類型是boost::shared_array,它的定義在boost/shared_arrary.hpp裡。#include <boost/shared_array.hpp>void test5(){ boost::shared_array<int> sa1(new int[2]);boost::shared_array<int> sa2(sa1);sa1[0]=1;std::cout<<sa2[0]<<" "<<sa2[1]<<std::endl;//1 -84150451} //對智能指標的良好運用可以有效處理記憶體,資源等自我管理釋放問題。對於現代C++來說,是必不可少的一件"神器"。同時在boost庫裡面也有廣泛應用,如在asio中,shared_ptr的使用就是其中一例。void test(char t){std::cout<<"press key====="<<t<<std::endl;switch (t){ case '1':test1();break; case '2':test2();break; case '3':test3();break; case '4':test4();break; case '5':test5();break; case 27:case 'q':exit(0);break;default: std::cout<<"default "<<t<<std::endl;break;}}int main(){while(1){test(getch());} return 0;}