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.

using namespace std;

class Handle;
class Base
    friend class Handle;
    Base() {}

class Handle
    static Handle TEST_OBJECT;

    Handle() : ptr(new Base)
        //gives same problem on pair insertion line:
        //    references[ptr].insert(this);
        //    set<Handle*> temp;
        //    temp.insert(this);
        //    references.insert(make_pair(ptr, temp));
    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!

Ahhhhh! The TEST_OBJECT's constructor was being called before the map's. That was all. *Shame...*

This article has been dead for over six months. Start a new discussion instead.