智能指標scoped_ptr

來源:互聯網
上載者:User

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();}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.