智能指標tr1::shared_ptr、boost::shared_ptr使用

來源:互聯網
上載者:User

標籤:shared_ptr   智能指標   類指標對象   tr1   boost   

對於tr1::shared_ptr在安裝vs同時會內建安裝,但是版本較低的不存在。而boost作為tr1的實現品,包含
“Algorithms
Broken Compiler Workarounds
Concurrent Programming
Containers
Correctness and Testing
Data Structures
Domain Specific
Function Objects and Higher-order Programming
Generic Programming
Image Processing
Input/Output
Inter-language Support
Iterators
Language Features Emulation
Math and Numerics
Memory
Parsing
Patterns and Idioms
Preprocessor Metaprogramming
Programming Interfaces
State Machines
String and Text Processing
System
Template Metaprogramming
Miscellaneous ”
等一系列更安全、更豐富的c++函數或庫的實現品。可以在官網下載,其中包含詳細的API文檔與常式。其中boost::shared_ptr是對tr1的shared_ptr的實現。作為智能指標(類指標對象)二者的使用方法相似,具體見下方代碼。

 

標頭檔
#include <iostream>using namespace std;class Test{public:Test();~Test();};

實現檔案
#include "head.h"Test::Test(){    cout << "construct Test." << endl;}Test::~Test(){    cout << "destruct Test." << endl;}

main檔案
//boost中shared_ptr標頭檔#include <boost/shared_ptr.hpp>//vs2005一併中安裝的庫是不帶shared_ptr的#include <memory>#include "head.h"//實驗tr1::shared_ptrvoid test_shared_ptr(){    cout << "I am tr1." << endl;    tr1::shared_ptr<Test> p_test(new Test());}//實驗boost/shared_ptrvoid test_boost_shared_ptr(){ cout << "I am boost." << endl;boost::shared_ptr<Test> p_boost_test(new Test());}int main(){    test_shared_ptr();    cout << "**************************" << endl;test_boost_shared_ptr();system("pause");}


 

執行效果:


上述兩種方式是使用對象管理資源的最佳實現,標準庫也提供了auto_ptr,但是這種對象不能夠複製。

對於使用對象管理資源的思路,C++t推薦的原則是RAII,即Resource aquisition is initialasition。

***************************************************************************

原創,本文連結:http://blog.csdn.net/u012150179/article/details/37965931

 

智能指標tr1::shared_ptr、boost::shared_ptr使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.