I'm having a hideous problem with a program I'm working on involving a map with pointer keys. The keys are pointers (to objects on the stack) and the data are pointers (to objects on the heap). It's the list of references for a handle class, so that if handle.destroy() is called (which should delete the base (heap) object the handle "points" to), all handles to the same object will be informed of this so as not to access the data any longer. The way the program works requires objects to be destroyed in certain instances OTHER than the destruction of all handles--IE, I'm implementing pointer safety and garbage collection without affecting the normal potential of an object's memory to be deallocated.
I've isolated the source of the problem to a specific line and written the shortest possible program that reproduces it. It compiles fine, but gives an access violation (segmentation fault) when run. Also, I've tested it just using a map<int*, int*> and adding elements in the same way, which gives no errors--as it should, since the standard mandates std::less produces a meaningful ordering for pointers of the same type. But I get the problem when I do it with classes this way.
#include<map>
#include<set>
using namespace std;
class Handle;
class Base
{
public:
friend class Handle;
private:
Base() {}
};
class Handle
{
public:
static Handle TEST_OBJECT;
Handle() : ptr(new Base)
{
//PROBLEM IS WITH THIS FOLLOWING LINE:
references[ptr].insert(this);
//gives same problem on pair insertion line:
//if(references.count(ptr))
// references[ptr].insert(this);
//else
//{
// set<Handle*> temp;
// temp.insert(this);
// references.insert(make_pair(ptr, temp));
//}
}
private:
static map<Base*, set<Handle*> > references;
Base* ptr;
};
Handle Handle::TEST_OBJECT;
map<Base*, set<Handle*> > Handle::references;
int main() { return(0); }
Does anybody know what the issue is and how it can be resolved? Thanks!