Re: hash_map elements deletion
lokki wrote:
Very likely, you corrupted the integrity of the map by deallocating all
the pointers. Does the comparision object / hash function for this map /
unordered_map access the pointees or just the stored pointers? If the
former is the case, the previous run through the list makes it very
likely that you enter undefined behavior.
Suggested fix: don't use char*, use std::string instead.
I would rather not use std::string because of performance issues in
target application. I tried to analyse that and came to folowing:
- The hash_map in target application will have to hold thousands of
strings.
- The container holds the copy of every object. In case of const
char * it holds only pointer, in case of std::string a complex
object.
- A lot of constructor/copy constructor calls will be neccesary when
inserting std::string to hash_map.
- Data from hash_map will be only read when once inserted. They
should be const, there is no necessity to change them. A very very
fast find is required.
- Almost every external library/ other code in applicaiton is using
const char * for strings.
- After usage, it is required to clear map and to load new data.
Hm, I always found that std::string is just as efficient as char* and
sometimes more efficient (since it stores a length and). Also, I find that
if performance becomes an issue, replacing std::string by some other string
implementation (conforming to the same or similar interface) allows for
better optimization than moving over to char*.
I have a previous implementation using std::string and trying to
rebuild it to const char*.
Any advice on safer initialisation/deletion of char pointers in
hash_map?
You could try this (untested):
void clear_char_ptr_map ( whatever_type_mp_was & mp ) {
TStringMapIterator j = mp.begin();
while ( j != mp.end() );
char* dummy_1 = j->first;
char* dummy_2 = j->second;
mp.erase( j++ );
delete [] dummy_1;
delete [] dummy_2;
}
}
It would probably be best if you designed your own map-class that owns the
strings and takes care of all memory management for you.
Best
Kai-Uwe Bux