boost smart_ptr -> scoped_ptr

scoped_ptr P78

C++98 的標準“自動指針”:std::auto_ptr

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

只能在本作用域內使用,不希望被轉讓。

a. 不支持比較操作
b. .swap()交換兩個scoped_ptr保存的原始指針,高效操作。
c. 缺陷:不能用作容器的元素

 scoped_prt<string> sp(new string("text"));
 cout<< *sp <<endl;
 cout<< sp->size() <<endl;  
 #include <iostream>
 #include <boost/assert.hpp>
 #include <boost/smart_ptr.hpp>

 using namespace std;
 using namespace boost;

 struct posix_file  //一個示範性質的文件類
 {
     posix_file(const char* file_name) //構造函數打開文件
     {
         cout << "Open file:" << file_name << endl;
     }
     ~posix_file()
     {
         cout << "close file" << endl;
     }

 };

 int main(int argc, char *argv[])
 {
     scoped_ptr<int> p(new int);
     if(p)               //在bool語境中測試指針是否有效
     {
         *p = 100;
         cout << *p << endl;
     }
     p.reset();          //reset()置空scoped_ptr,僅僅是演示
     assert(p == 0);     //p不持有任何指針
     if(!p)
     {
         cout << "scoped_ptr == null" << endl;
     }

     //文件類的scoped_ptr
     //將在離開任用域時自動析構,從而關閉文件釋放資源
     scoped_ptr<posix_file> fp(new posix_file("/tmp/a.txt"));

     return 0;
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章