How can I free a pointer vector?

How can I free memory in a pointer vector? Here is the code:

class A
{
    private:
        int x,y,z;
    public:
        A(param1, param2, param3)
        {
            x=param1;
            y=param2;
            z=param3;
        }
        ~A()
        {
            //prompts an alertbox, warning me about the successful call of the destructor;
        }
};

...
vector<A*> list;
list.push_back(new A(1,2,3));

list.erase(list.begin()+index);//SHOULD delete the object from the memory;
list.clear();

I found out that it .erase()does not free memory, and does not call the destructor; I tried to use deleteiterated list in every entry, but failed after one iteration. Already checked if the list entry was already NULL to avoid any error. Am I missing something? In addition, I should use only STL, no Boost needed.

+5
source share
6 answers

list.erasefree memory for its member elements (and call their destructors, if they exist); he will not call deleteon them.

A Boost shared_ptr . , , list delete erase. - :

void my_delete(A *p)
{
    delete p;
}

...

std::for_each(list.begin(), list.end(), my_delete);
+8
for( std::vector<A*>::iterator i = list.begin(), endI = list.end(); i != endI; ++i)
{
   delete *i;
}
list.clear();

, -

std::for_each( list.begin(), list.end(), []( A* element) { delete element; });
list.clear();
+4

erase , (), , .

, , .

Boost ptr_vector.

+3

STL , . , . , , . . , ; std::shared_ptr , . . : std::vector< std::shared_ptr<A> >

/std lib std::shared_ptr, ++, . , , std::tr1::shared_ptr, TR1 2003 . ( , boost boost_shared_ptr, .)

STL, . , ( ) return , . ( , , .)
- PITA, .

+2

, , ++. , , , , . , , . , :

#include <vector>
#include <algorithm>

class A
{
    int x,y,z;

public:
    A (int param1, int param2, int param3) :
        x (param1), y (param2), z (param3)
    {
    }
};

struct Deleter
{
    template <typename T>
    void operator () (T *obj) const
    {
        delete obj;
    }
};

int
main ()
{
    std::vector<A*> list;

    list.push_back (new A (1, 2, 3));
    list.push_back (new A (4, 5, 6));
    list.push_back (new A (7, 8, 9));

    std::for_each (list.begin (), list.end (), Deleter ());
    list.clear ();
}

Boost Ptr Container, . ++ 0x std:: unique_ptr, STL .

+1
for(size_t i = 0; i < list.size(); ++i)
{
    delete list[i];
}

list.clear();

If you do something like this and your code crashes, send the exact code and crash information.

0
source

All Articles