繁体   English   中英

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

[英]Do I need to deallocate object pointers in a vector?

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

vector<Object*> vec;

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

//DEALLOCATE CODE HERE//

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

避免使用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将负责删除

如何解除分配

例如做

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)

所有分配的内存已释放

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM