Pointers As Map Key In Static Map Member

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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!
The Handle() constructor is being called before the map constructor.

Switch the order of lines 38 and 39 and see if that fixes the problem.
That's EXACTLY it. The program the problem showed up in is so big and involved I didn't even think about that... How embarrassing.

Thanks a lot!
Last edited on
Keep in mind that construction order of global/static variables is guaranteed on a per-translation unit basis only. That is, within a single source file the order in which variables are instantiated is the order in which their constructors will run. But if 2 globals are in two different source files, the construction order is undefined.
Topic archived. No new replies allowed.