標籤: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使用