The problem of freeing a vector compared to an array

I store dynamically assigned class pointers in a vector, as shown below.

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

Now, if I need to free Test objects, I have to skip the whole vector and free one by one, and then make it clear.

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

Is there any function in the vector for freeing all internal objects. This function should call the destructor of the Test class for each object. I understand that it is difficult for the Vector class to determine if the pointer is a local object address or dynamically allocated. But still, whenever a developer is sure that everyone is dynamically allocated, he could use the release function, if one is provided.

, , .

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

- ?

+3
5

.

:

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

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

, , :

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

:

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

:

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

, . .

, , . , , ( , , delete[])

, - - . , .

+4

, , a std::vector delete .

, , , , , , . , boost::ptr_vector .

+2

- . ++ .

:

  • free'ing ( shared_ptr unique_ptr ++ 0x, ). Boost ptr_vector, , .

  • delete ( ).

(: , )

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 );
}
+2

, vector , . , , , .

, shared_ptr. , shared_ptr . , :

#include <functional>

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

, vector<Foo*>, :

#include <algorithm>

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

boost, ptr_containers, , .

+1

I asked the same question before, and I was asked to use the Boost library, and you will find some great tips here, or just you can understand smart pointers like this:

Instead of having a vector of pointers, you will have a vector of smart pointers, since for every new one you make it, it will delete itself without worrying.

0
source

Source: https://habr.com/ru/post/1760729/


All Articles