I've been working on a Qt project and I encountered a problem with deleting objects that are being hold in a map. I prepared a simple C++ code to show my problem:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class A
{
public:
int *tab;
A()
{
tab = NULL;
}
~A()
{
if (tab != NULL)
{
delete[] tab;
}
}
};
int main()
{
map<string, A> mapa;
string name = "MyArray";
A *a = new A;
a->tab = new int[3];
a->tab[0] = 1;
a->tab[1] = 2;
a->tab[2] = 3;
mapa[name] = *a;
delete a;
system("PAUSE");
return 0;
}
After closing the program I get: Debug Assertion Failed!
_BLOCK_TYPE_IS_VALID etc..
My question is: why is that? The reason is probably that map gets deleted after I quit the program and it holds an A object (a) that is being deleted before I close the program. However, I passed a value, not an address, so what's the problem?
Isn't that value just copied into the map and held in some different address?