将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;
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐