Sriram Krishnan (Moved to http://www.sriramkrishnan.com/blog)

Search. Usability. Virtual machines.Geek stuff

<August 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456


Navigation

Subscriptions

News

Link blog
Technorati Profile
The Blogs I read
Creative Commons Licence
This work is licensed under a Creative Commons License.


STL newbie mistakes

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!]

posted on Monday, February 28, 2005 11:46 PM by sriram





Powered by Dot Net Junkies, by Telligent Systems