scoped_ptr特點:
1 用法絕大多數情況下和auto_ptr相同。
2 不支援自增,自減操作。
3 不能被賦值或者複製構造。
4 由於3的原因不能作為容器的元素,這也是優於auto_ptr的原因。
scoped_ptr使用情境:
1 在有可能拋出異常的範圍中使用時,減少有可能資源釋放不正確導致的錯誤。
2 函數中控制路徑多並且複雜時,減少代碼的邏輯閱讀難度和資源釋放有可能帶來的錯誤。
3 動態指派至的生命週期限制在特定的範圍,採用scoped_ptr可以有範圍保護。
4 異常安全非常重要的時候,作用類似於1
示範代碼:
// scoped_ptr.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <boost/scoped_ptr.hpp>#include <string>#include <iostream>#include <vector>using namespace std;using namespace boost;void scoped_vs_auto();int _tmain(int argc, _TCHAR* argv[]){// 正常用法scoped_ptr<string> p(new string("User scoped_ptr often."));if (p){cout << *p << '\n';cout << "sizeof(\"" << *p << "\") = " << p->size() << endl;*p = "Acts just like a pointer";cout << "After Change:" << endl;cout << "sizeof(\"" << *p << "\") = " << p->size() << endl;}// 自增自減操作——不支援//p++;//p--;// scoped_ptr和auto_ptr的比較// scoped_ptr不能被賦值或複製構造scoped_vs_auto();// 因為不支援賦值和複製構造,所以不能作為容器的元素//vector<scoped_ptr<string>> vecp;//vecp.push_back(p);// scoped_ptrgetchar();return 0;}void scoped_vs_auto(){scoped_ptr<string> p_scoped(new string("hello"));auto_ptr<string> p_auto(new string("hello"));p_scoped->size();p_auto->size();// 編譯不通過,不能被賦值//scoped_ptr<string> p_another_scoped = p_scoped;auto_ptr<string> p_another_auto = p_auto;p_another_auto->size();(*p_auto).size();}