Some times you have to hurt him to save him

Just spent a fair amount smacking myself in the head for the following bug:

    //first check if it's in our cache.

    CGenericMemberDataPtr spSynthesizedMember;

    if ( ! m_memberCache.Lookup(iMember, spSynthesizedMember))


        //wasn't in the cache, have to create it





        CGenericMemberDataPtr spSynthesizedMember = new CGenericMemberData(...);

        m_memberCache.SetAt(iMember, spSynthesizedMember);



    CMemberDataPtr spCachedMD = spSynthesizedMember->Clone();

Pretty basic stuff.  A lookup into a cache (for perf reasons) and a lazy creation of an item if it wasn't found.  But wait!  Go me!  I redclared the spSynthesizedMember variable in a nested block and so my assignment wasn't visible and it was only the addition of the below code that triggered this when it tried to derference null.  This is one of those cases where I like the C# rules even if they can be pretty restrictive if you've come from a language that allows this.

Of course, I'd just be happy if the C++ compiler could warn on this sort of code so I could catch these bugs a lot faster.

Comments (5)
  1. Brian Duff says:

    Ew… I’ve been using Java so long I had totally forgotten you could do that in C++ 🙂 Long live Java (and C# 😛 )

  2. Funny, C# saved me from just that very thing today – fixed some code to add a using block for a StreamWriter, copied one instance assignment out above the using block, had the compiler complain to me about the variable already being declared 🙂

  3. maorachow says:

    woow,I have the problem either.That is the scope of variables.Sometimes it isnot a bad thing,you have to hurt him to save him,donot you?C++ is the sort of such style!

  4. Mitch Denny says:

    You must have been feeling sheepish 🙂 I didn’t spot it though 🙂

Comments are closed.

Skip to main content