I'd like to use the map for key/member search, the problem is that the class contains a member of buffer allocated by the malloc call.
struct Key {
int key1;
int key2;
bool operator < (Key & a) { .... }
};
struct Entity {
unsigned char *data;
};
typedef std::map(Key, Entity) TMap;
Then I can insert data with key like:
Tmap map;
Key key;
Entity ent;
ent.data = malloc(size);
key.key1 = xx;
key.key2 = xx;
map.insert( ...(key,ent));
The problem is that I'd like the "ent.data" pointer automatically freed when map is deleted. Also at the same time, I want I can access the "data" when do a map find operation to read the buffered data.
I tried to add destructor to the struct Entity, but it seems it leads to some duplicated free issue.
What's the solution?
[Solution]: 1. use shared_ptr:
typedef std::tr1:shared_ptr(unsigned char) CharPtr;
struct Entity {
CharPtr data;
}
ent.data = CharPtr((unsigned char*)malloc(size), free);
Or another solution. Use Vector as Eugene Homyakov mentioned.