Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release std::vector if there is no heap memory

I have a class member variable like this:

vector<vector<int> >  m_stacks;

When I populate it, I do like this:

vector<int> v;
v.push_back(1);
v.push_back(2);
m_stacks.push_back(v);
vector<int> v2;
v2.push_back(1);
v2.push_back(2);
m_stacks.push_back(v2);

Now I am wondering what I should do in the class destructor to release m_stacks. I do not allocate any heap memory for it, so I am struggling if I really need to do anything. Finally I come up this -

vector<vector<int> >::iterator itr = m_stacks.begin();
for ( ; itr != m_stacks.end(); ++itr) {
  itr->clear();
}

I think this is the most I need to do, I do not need to call m_stacks.clear(). The reason is vector's destructor can automatically release the memory. But I still need the above code though, the reason is vector's destructor does not call its element's destructor.

Could you confirm my call?

like image 329
my_question Avatar asked Oct 28 '11 04:10

my_question


3 Answers

You don't have to do anything for m_stacks (a class data member). Acquired memory will be released automatically when the class destructor will be called. This is the purpose for which std::vector is used.

like image 78
iammilind Avatar answered Nov 04 '22 06:11

iammilind


The destructor for a vector will do two things: it will destroy each element of the vector, then it will free the memory used for the vector itself. This is automatic.

In your case you have vectors nested two deep, but it doesn't matter. When the top level vector is destroyed it will call the destructor for each vector it contains, and all of those vectors will clean themselves up properly.

like image 29
Mark Ransom Avatar answered Nov 04 '22 07:11

Mark Ransom


The std::vector destructor calls a delete on the memory it allocates, thereby calling that types (in this instance, a std::vector<int>'s) destructor.

These data structures all rely on SBRM (Scope bound resource management), or RAII (Resource acquisition is initialisation) principles, in that all memory they allocate is de-allocated once they go out of scope (such as the scope of a class).

You do not need to worry about the releasing of memory from a std::vector unless it holds a type which points to memory; but does not release it inherently (such as a pointer!).

like image 25
deceleratedcaviar Avatar answered Nov 04 '22 05:11

deceleratedcaviar