I feel really stupid after making 2 newbie STL mistakes. Next time, I promise that I'll read the documentation first before assuming that the a data structure would work similar to the equivalent in .NET/Python whatever
Container objects and pointers
Container objects run the destructor on their member objects when they destruct. However, if you're storing *pointers*, the destructors won't be called. If you don't call them manually, you'll have a memory leak. Lots of ways to solve this - using shared_ptr from the Boost library is probably the best. I personally wrote a wrapper because Boost introduces other problems for me.
Using character pointers as the key in a map or a hash_map
Basically..don't! Character pointers are bad,bad in C++ and if you're forced to use them like I am, read the following carefully.
If you do something like map<const char*, value>, you won't get the results you're looking for. STL will compare *the pointers* rather than the string itself. The best way around this is to use the inbuilt string objects or pass a custom comparer class.This is what I'm using - may be buggy but it seems to work for now
class WStringCmp
{
public:
bool operator() ( const WCHAR* s1, const WCHAR* s2 ) const
{
while( *s1 && *s2 && *s1 == *s2 )
{
s1 ++;
s2 ++;
}
return (*s1 < *s2);
}
};
[Update: This code actually has a bug in it, believe it or not! See
this post. Also, thanks Deepak for the conversation which led me to spot this bug!]