How to correctly design the destructor

Hello everybody!

In one of my classes I have the following member variable:

vector<vector<TData> * > * _timeSeries;

My question is how to design the destructor for this variable. I have now the following:

1
2
3
4
5
6
if (_timeSeries != NULL){
  for (TIndex i=0; i<_timeSeries->size(); i++){
    (*_timeSeries)[i]->clear();
  }
  delete _timeSeries;
}


Is that correct? I am not sure if I can use the clear function or if I also have to use delete there. I appreciate your comments. :)
Each element inside _timeSeries is vector<TData> * so I presume somewhere in your code you did something say like below

(*_timeSeries)[i] = new vector<TData>();

?

Then you should add the delete isn't it ? clear is a method from vector that clears the contents of the vector but delete is to de-allocate the memory you have new'ed in the above.

1
2
(*_timeSeries)[i]->clear();
delete (*_timeSeries)[i];


?
The description of the clear function says:

"All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0."

But this would still occupy some memory, as I still have a vector (even if it has size 0), right?
Yeah, calling delete directly seems reasonable. Thanks!
I am no expert in how C++ handle memory allocation and de-allocation but I read from Scott Meyers C++ book is do not assume how C++ does it. If your code has a "new <object>" then somewhere down the road there should be a corresponding "delete <object>". By following this principle faithfully, you obey the C++ rules and C++ in theory will do the correct job of memory de-allocation for us.

Lastly, I think a vector with size 0 still occupy memory. The size 0 only say it contains no elements but the internal implementation of vector may have some variable pointers or other memory related data structures and those are not free-ed.
Topic archived. No new replies allowed.