Sort of continuation of my question here: Freeing twodimensional arrays stored in a map Tried to follow the suggestion of wrapping my 2D array into a class with destructor and coincidentally managed to reproducably generate an error similar to my project, in the minimal sample. Not all consoles seem to print it (and show weird behavior), but this one does: https://onlinegdb.com/BkhPN6TbL
#include <iostream>
#include <string>
#include <map>
int w = 20;
int h = 20;
class RawGrid
{
public:
RawGrid(int w, int h)
{
width = w;
data = new bool*[w];
for(int x = 0; x < width; x++)
data[x] = new bool[h];
}
~RawGrid()
{
if (data)
{
for(int x = 0; x < width; x++)
delete[] data[x];
delete[] data;
}
}
private:
int width;
bool** data = nullptr;
};
int main()
{
std::cout<<"Test A" << std::endl;
{
RawGrid grid_a(w, h);
std::cout<<"Reserved memory" << std::endl;
}
std::cout<<"Deleted memory" << std::endl; // because grid_a is out of scope
std::cout<<"Test B" << std::endl;
RawGrid grid_a(w, h);
RawGrid grid_b(w, h);
std::map<int, RawGrid> cache_map;
cache_map.emplace(0, grid_a);
cache_map.emplace(1, grid_b);
std::cout<<"Reserved memory" << std::endl;
cache_map.clear();
std::cout<<"Deleted memory" << std::endl;
return 0;
}
The error appears to depend on the delete[] data;
line (no error if I remove it) but it appears to only happen if used within a map (as Test A shows). How would I safely deconstruct this class?