STL容器的内存管理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/how0723/article/details/82959484
class Unit
{
public:
	Unit();
	Unit(int id);
	~Unit();

private:
	int id = -1;
};

Unit::Unit()
{
}

Unit::Unit(int _id) :id(_id){
	printf("Unit construction. id=%d\n", id);
}


Unit::~Unit()
{
	printf("Unit destruction. id=%d\n", id);
}

1、如果容器中保存了对象指针,则要在清除容器前手动删除指针,否则就会内存泄露。


	std::vector<Unit*> units;
	units.reserve(100);
	for (int i=0;i<3;++i)
	{
		units.push_back(new Unit(i));
	}

	for (Unit* ptr:units)
	{
		delete ptr;
		ptr = nullptr;
	}

2、如果容器中保存了对象,存在多次复制的问题。建议存储指针。

猜你喜欢

转载自blog.csdn.net/how0723/article/details/82959484