std::vector erase 没有清除对象的问题

//vector 存储对象的时候删除后释放内存,存储对象指针的时候删除后并不释放内存
#include 
#include 

using namespace std;

class Test
{
public:
	Test(int i) ;
	~Test() ;

private:
	int id;
};

Test::Test(int i)
{
	id = i;
	printf("%d construct\n",i);
}

Test::~Test()
{
	printf("%d destruct\n",id);
}

int main() {
	vector vec1;
	for (int i = 0; i < 3; i++)vec1.push_back( Test(i));
	printf("before erase\n");
	vec1.clear();
	printf("after erase\n\n");

	vector vec2;
	for (int i = 0; i < 3; i++)vec2.push_back(new Test(i));
	printf("before erase\n");
	vec2.clear();
	printf("after erase\n\n");

	vector vec3;
	for (int i = 0; i < 3; i++)vec3.push_back(new Test(i));
	for (int i = 0; i < 3; i++)delete vec3[i];
	printf("before erase\n");
	vec3.clear();
	printf("after erase\n\n");

	system("pause");
	return 0;
}

std::vector erase 没有清除对象的问题_第1张图片

你可能感兴趣的:(C++,STL)