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.
newand notmallocin c++. AndSTL containers do not take the responsibility of deallocating an element which is allocated on the freestore. Which means you would have to deallocate them explicitly. The best way to achieve this is using smart pointers, Using smart pointers you do no have to free the dynamic memory explicitly but the elements themselves take care of deallocating its own resources.
The RAII/SBRM feature of C++ was explicitly designed for avoiding problems such as the one you are facing.