How do i can free mamory in next example.
vt.pop_back() deletes element in vt, but it doesn’t free memory.
delete vt[i] doesn’t work, and it give me segmentation fault.
#include <vector>
#include <unistd.h>
using namespace std;
const int SIZE = 1000000;
class Test
{
public:
Test();
~Test();
private:
int *arr;
};
int main()
{
vector<Test *> vt;
for(int i = 0; i < 100; i++)
vt.push_back(new Test());
sleep(10);
return 0;
}
Test::Test()
{
arr = new int[SIZE];
}
Test::~Test()
{
delete[] arr;
}
You are not storing “Test” objects, you are storing pointers to these objects. So delete does nothing but delete the pointers.
If you want your objects to be stored in the vector you should make the type
This way the delete calls actually run the destructor of the objects.
The resulting code becomes:
As commented this also requires a new copy constructor: