How can I free up memory in a pointer vector? Here's 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 .erase()
doesn't free up memory, neither calls the destructor; I tried to use delete
on every list entry with an iteration, but crashes after one iteration. Already checked if the list entry was already NULL, to avoid any error.
Am I missing something?
Also, I must use only STL, don't need Boost.
list.erase
will deallocate the memory for its member elements (and call their destructors, if they exist); it will not call delete
on them.
A Boost shared_ptr
would be the obvious way of doing this. If you don't want to use that, you're either going to write your own smart-pointer class, or iterate through list
and call delete
on each pointer before calling erase
. You can do this neatly with something like:
void my_delete(A *p)
{
delete p;
}
...
std::for_each(list.begin(), list.end(), my_delete);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With