boost库的智能指针shared_ptr结合容器vector的使用
将n个shared_ptr放在vector中,vector会保持每个shared_ptr的引用;vector销毁时,shared_ptr会自动销毁所持对象,释放内存#include#include#includeusing namespace std;class A{public:A(int i):num(i){}int getNum() { return num;
·
将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;
}
更多推荐
已为社区贡献1条内容
所有评论(0)