Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector freeing issue compared to array

Tags:

c++

I am storing dynamically allocated class pointers in a vector like below.

     vector<Test *> v;
    Test *t1 = new Test;
    Test *t2 = new Test;
    v.push_back(t1);
    v.push_back(t2);

Now, if i have to free Test objects, i have to loop through entire vector and free one by one and then do a clear.

for(int i = 0; i<v.size(); i++)
     {
         delete v[i];
     }
     v.clear();

Is there any function in vector to free all internal objects. That function should call Test class destructor for each object. I understand that it is difficult for Vector class whether the pointer is address of a local object or dynamically allocated. But still, whenever developer is confident that all are dynamically allocated he could have used freeing function if provided.

Although vector is treated as advanced Array, freeing objects in an array is much easier like below.

Test  *a = new Test[2];
delete []a;

Is there any function in vector to free all internal objects ?

like image 398
bjskishore123 Avatar asked Apr 19 '26 04:04

bjskishore123


1 Answers

Your examples don't do the same thing at all.

If you want the vector equivalent of this array code:

Test  *a = new Test[2];
delete []a;

it is simply

std::vector<Test> a(2);

If you have a vector of pointers to dynamically allocated objects, you need to delete every one of them, as in your example:

for(int i = 0; i<v.size(); i++)
 {
     delete v[i];
 }

but the same thing is true for an array:

Test *t1 = new Test;
Test *t2 = new Test;
Test **a = new Test*[2];
a[0] = t1;
a[1] = t2;

also has to be deleted with such a loop:

for(int i = 0; i<2; i++)
 {
     delete a[i];
 }
delete[] a;

In the first case, you have two objects stored in a container of some sort. That container may be a vector, or it may be an array.

In both cases, because the objects are stored directly in the container, their destructors are called when the container is destroyed. You don't need to do anything to destroy or delete individual members, you just have to destroy the container (which is simpler with the stack-allocated vector, where you don't even need to call delete[])

But if your container stores pointers to dynamically allocated objects, then it is your responsibility to delete those objects at some point. And that is true whether your container is an array or a vector.

like image 164
jalf Avatar answered Apr 21 '26 18:04

jalf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!