About Destroying and Clearing A Vector

Feb 3, 2009 at 1:28pm
Hi,

Suppose I have the following vector

 
vector<T> v;


and I am wondering what is the difference
between emptying the vector with this:

 
v.clear();


versus this destructor:

 
v.~vector<T>();


When should we use destructor instead of clear() ?
Feb 3, 2009 at 2:06pm
You should never* call the destructor explicitly.

But they are different anyway, in that clear does not release the underlying memory that was allocated to the vector.

*-99.999999999999% of the time. Ok, vector<> does funny things internally where it has to do it explicitly, but that is not the norm.

Feb 3, 2009 at 6:24pm
You clear the vector when you want to continue to use the object for other purposes. You can clear the object and then fill it again. If you destroy the object, it is gone and you would have to construct a new one. As jsmith indicates you never call the destructor explicitly. The destructor is called when a stack allocated object goes out of scope at the end of a block or when you explicitly delete the object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void function()
{
   std::vector<int> myArray;
   {
      // fill the array with 10 values.
      myArray.push_back(i);
   }
   // The object still exists.  You simply cleared it.  You can still use 
   // myArray to fill it with new values if you would like.
   myArray.clear();

   // When function exits destructor for myArray is called automatically.
   // if myArray had been allocated using "new std::vector<int>"
   // you'd have to call "delete myArray" when ready to call the destructor.
}
Topic archived. No new replies allowed.