boost庫的智慧指標shared_ptr結合容器vector的使用
阿新 • • 發佈:2019-01-28
將n個shared_ptr放在vector中,vector會保持每個shared_ptr的引用;vector銷燬時,shared_ptr會自動銷燬所持物件,釋放記憶體
#include <iostream> #include <boost/shared_ptr.hpp> #include <vector> using namespace std; class A { public: A(int i):num(i){} int getNum() { return num; } ~A() { cout << num << " destroy" << endl; } private: int num; }; int main() { vector<boost::shared_ptr<A> > vsa; for(int i = 0; i < 5; ++i) { boost::shared_ptr<A> x(new A(i)); vsa.push_back(x); } for(size_t i = 0; i < vsa.size(); ++i) { std::cout << vsa[i]->getNum() << " "; } cout << endl; }