0

I read that STL containers will allocate elements in the heap but the container objects are allocated in the stack.

Therefore, in the code below do I need to first clear off the elements of vector "vec" from the heap before deleting "sub" in order to avoid memory leak?

Or, does the STL vector destructor gets called when "sub" gets deleted and it takes care of clearing off the elements from the heap by default?

For sure, if I declared a vector like: std::vector<int> *v = new std::vector<int>(); then I would need to do a delete v. Can anyone help clarify my confusion.

Here is the code:

struct Subscriber {
int cmd;
std::vector<int> vec;
};

Subscriber *sub = new Subscriber();
sub->vec.clear();
delete sub;

Thanks,
Symon.

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by sarehu
0

No you don't. When a vector's destructor gets called, it calls the destructors of all its elements.

0

For example, the behavior of the following two snippets is more or less the same, as far as destruction is concerned:

T* p = new T[3];
p[0] = x;
p[1] = y;
p[2] = z;
delete[] p;
{
  std::vector<T> v;
  v.push_back(x);
  v.push_back(y);
  v.push_back(z);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.