3

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 ?

bjskishore123
  • 6,144
  • 9
  • 44
  • 66
  • Might I comment that it's clearer to write `Test* a = ...` and `delete[] a;`, in the first case, the type is a pointer to a Test (actually an array, but in general it is better in my opinion to write the type as one piece: `Class* someObject`), and in the second case, you're using operator `delete[]` on `a`, not operator `delete` on `[]a`, which is not nearly the same. – rubenvb Aug 20 '10 at 12:05

5 Answers5

4

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.

jalf
  • 243,077
  • 51
  • 345
  • 550
  • @rubenvb: it deletes the array. But if the array stores pointers, it won't delete what those pointers point to. – jalf Aug 20 '10 at 12:19
  • @jalf: aha, I understand now. Another reason to not use an array. – rubenvb Aug 20 '10 at 13:04
  • @jalf: I am getting error for below line a[0] = t1; as i did not overload assignment operator in Test class. How do you define assignment operator in this case ? – bjskishore123 Aug 20 '10 at 13:07
  • @jalf: also if a[0] and t1 both are same, is it correct to do like below ? for(int i = 0; i<2; i++) { delete a[i]; } delete[] a; – bjskishore123 Aug 20 '10 at 13:31
  • @bjskishore123: sorry, I had a typo. The type of `a` should have been `Test**`, since it is a pointer to a range of Test *pointers*, just like you created a vector of Test pointers. It should be fixed now. To your second comment, yes, that is correct. `a[0]` and `t1` both point to the same object, so it doesn't matter which of them you call `delete` on. – jalf Aug 20 '10 at 15:29
2

No, there is no way to request that a std::vector full of pointers automatically call delete on all of its elements.

There are, however, other, third-party containers that will make this sort of thing easier by automatically deleting pointers when they are removed from the vector, or when the vector destructs. For example, boost::ptr_vector and friends.

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
2

The short answer is no. C++ does not provide a vector of pointers free'ing function.

The long answer is twofold:

  1. Use smart pointers, and forget about free'ing (there's shared_ptr or unique_ptr in c++0x that will serve most of your needs). Alternatively, use a Boost ptr_vector like Tyler suggested.

  2. It's not that hard to write a simple generic algorithm to delete each item in a container (use a template with iterators).

(warning: untested code, have no time to check it)

template<class It>
void delete_clear_ptr_cont( const It &beginIt, const It &endIt )
{
    for( auto it = beginIt; it != endIt; ++it )
    {
        delete it;
    }
    erase( beginIt, endIt );
}
rubenvb
  • 74,642
  • 33
  • 187
  • 332
1

No, vector isn't aware that it may be instantiated with pointers. And even if it was, there are situations where you don't own the pointers and you don't want the delete behavior.

In most cases we simply use a vector of smart pointers, like shared_ptr. However, there are times where shared_ptr isn't appropriate. For those cases we have a functor in our toolbox like this:

#include <functional>

template<typename T>
struct PointerDelete : public std::unary_function<T*, T*>
{
   T* operator()(T*& p) const
   {
      delete p;
      return 0;
   }
};

Then, assuming you have a vector<Foo*>, you could do either:

#include <algorithm>

std::for_each(v.begin(), v.end(), PointerDelete<Foo>());
// or
std::transform(v.begin(), v.end(), v.begin(), PointerDelete<Foo>());

If you can use the boost library, there are also ptr_containers, which are containers that take ownership of pointers and do the delete for you automatically on container destruction.

Brian Neal
  • 31,821
  • 7
  • 55
  • 59
0

I asked the same question before and I was suggested to use Boost library and you will find great tips here or simply you can understand smart pointers as follows :

Instead of having a vector of pointers you will have a vector of smart pointers , as for each new you will make it will delete itself without you having to worry .

Community
  • 1
  • 1
Ahmed
  • 3,398
  • 12
  • 45
  • 64