简体   繁体   English

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

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

I'm confused as to how deallocating vector memory works. 我对取消分配矢量内存的工作方式感到困惑。 For the example below, 对于下面的示例,

vector<Object*> vec;

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

//DEALLOCATE CODE HERE//

What should I do to deallocate vec properly? 我应该怎么做才能正确释放vec? The program seems to run fine as it is but I'm not sure. 该程序似乎可以正常运行,但是我不确定。

avoid using new/delete : 避免使用new / delete:

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

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

the unique_ptr will take care of deletion unique_ptr将负责删除

how deallocating 如何解除分配

for instance do 例如做

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

Note you written push_pack rather than push_back to fill the vector 请注意,您编写的是push_pack而不是push_back来填充向量


making a full program : 制作完整的程序:

#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();
}

Compilation and execution under valgrind : 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)

all allocated memory was freed 所有分配的内存已释放

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

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