当 vector 存储指针时,释放内存应该对每个元素进行 delete,然后 clear(),将容器元素清空

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <set>
#include <memory>
#include <vector>
#include <assert.h>

using namespace std;



int main()
{
	vector<int> number{1,3,5,7};
	vector<int *> integer;
  transform(number.begin(), number.end(), back_inserter(integer), 
  	[](const int &x){
  		int *y = new int(x);
  		(*y)++;
  		return y;
  	});
  cout << "Value :\n";
  for (auto x : integer) {
  	cout << *x << "\n";
  }
  cout << "Pointer :\n";
  for (auto x : integer) {
  	cout << x << "\n";
  }

  for (auto x : integer) {
  	delete x;
  }
  integer.clear();
  cout << "size, capacity is:\n";
  //size become 0, but capacity still not change
  cout << integer.size() << " " << integer.capacity() << "\n";
  

  //if want release capacity, should shrink_to_fit
  integer.shrink_to_fit();//vector<int*>(integer).swap(integer);
  cout << integer.size() << " " << integer.capacity() << "\n";

  int *a = new int(1);
  cout << a << "\n";
  delete a;
  return 0; 
}

输出:

Value :
2
4
6
8
Pointer :
0x7fae4e4026e0
0x7fae4e402700
0x7fae4e4026f0
0x7fae4e402710
size, capacity is:
0 4
0 0
0x7fae4e4026e0
Logo

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

更多推荐