简体   繁体   中英

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? The program seems to run fine as it is but I'm not sure.

avoid using 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

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


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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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