我是否需要在向量中取消分配对象指针?

时间:2019-04-07 21:26:20

标签: c++ memory vector

我对取消分配矢量内存的工作方式感到困惑。 对于下面的示例,

vector<Object*> vec;

for(int i = 0; i < 10; i++){
  Object* obj = new Object();
  vec.push_pack(obj);
}

//DEALLOCATE CODE HERE//

我应该怎么做才能正确释放vec? 该程序似乎可以正常运行,但是我不确定。

2 个答案:

答案 0 :(得分:1)

避免使用new / delete:

std::vector<std::unique_ptr<Object>> vec;

for(int i = 0; i < 10; i++)
{
  vec.push_pack(std::make_unique<Object>());
}

unique_ptr将负责删除

答案 1 :(得分:0)

  

如何分配

例如做

for(auto o : vect){
  delete o;
}
vect.clear();

请注意,您写的是push_pack而不是push_back来填充矢量


制作完整程序:

#include <vector>
using namespace std;

class Object{};

int main()
{
  vector<Object*> vec;

  for(int i = 0; i < 10; i++){
    Object* obj = new Object();
    vec.push_back(obj);
  }
  for(auto o : vec){
    delete o;
  }
  vec.clear();
}

valgrind 下的编译和执行:

pi@raspberrypi:/tmp $ g++ v.cc
pi@raspberrypi:/tmp $ valgrind ./a.out
==9157== Memcheck, a memory error detector
==9157== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9157== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==9157== Command: ./a.out
==9157== 
==9157== 
==9157== HEAP SUMMARY:
==9157==     in use at exit: 0 bytes in 0 blocks
==9157==   total heap usage: 16 allocs, 16 frees, 20,358 bytes allocated
==9157== 
==9157== All heap blocks were freed -- no leaks are possible
==9157== 
==9157== For counts of detected and suppressed errors, rerun with: -v
==9157== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

所有分配的内存已释放