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.

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

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);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.