<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>jaredpar's WebLog : C++</title><link>http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx</link><description>Tags: C++</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Type safety issue when assigning CComPtr&lt;T&gt; instances</title><link>http://blogs.msdn.com/jaredpar/archive/2009/11/04/type-safety-issue-when-assigning-ccomptr-t-instances.aspx</link><pubDate>Wed, 04 Nov 2009 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9916908</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9916908.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9916908</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9916908</wfw:comment><description>&lt;p&gt;Recently while making a bug fix to our selection tracking code I discovered an unexpected behavior with CComPtr&amp;lt;T&amp;gt; instances.&amp;#160; The crux of the fix included creating a new tracking mechanism exposed via COM in the type ISelectionTracking.&amp;#160; The old interface, lets call it IOldTracking, was a completely unrelated interface in terms of inheritance hierarchies.&amp;#160; &lt;/p&gt;  &lt;p&gt;As part of the fix I changed the type of a field (m_spTracking) from CComPtr&amp;lt;IOldTracking&amp;gt; to CComPtr&amp;lt;ISelectionTracking&amp;gt;.&amp;#160; I searched for assignments of m_spTracking and converted them to call the new API I added as part of the fix.&amp;#160; I didn’t search terribly hard because I was depending on the compiler to catch any places I missed.&amp;#160; ISelectionTracking and IOldTracking are incompatible types so any places I missed will show up as compilation errors.&amp;#160; &lt;/p&gt;  &lt;p&gt;Or so I thought … &lt;/p&gt;  &lt;p&gt;I made my fix, ran our core check-in suites without error, checked in and moved onto the next bug.&amp;#160; A couple hours later one of our other devs emailed me and informed me my check-in was breaking our larger, slower, suite bed run because m_spTracking was NULL. After some quick debugging I found myself looking at the following chunk of code which was apparently NULL’ing out m_spTracking in the suite.&lt;/p&gt;  &lt;pre class="code"&gt;  CComPtr&amp;lt;IOldTracking&amp;gt; spOldTracking;
&lt;span style="color: blue"&gt;  if &lt;/span&gt;( SUCCEEDED(CreateOldSelectionTracking(&amp;amp;spOldTracking)) ) {
    m_spTracking = spOldTracking;
  }
 &lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Me and the other dev were quite shocked that this compiled at all.&amp;#160; How is it possible to assign between CComPtr&amp;lt;ISelectionTracking&amp;gt; and CComPtr&amp;lt;IOldTracking&amp;gt;???&amp;#160; My first thought was I must have accidentally used a CComQIPtr somewhere (quickly verified that was not the case).&amp;#160; After a bit of searching we found the cause was one of the operater=&amp;#160; instances available on CComPtr&amp;lt;T&amp;gt;.&amp;#160; Here is the definition&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;template &lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;typename &lt;/span&gt;Q&amp;gt;
T* &lt;span style="color: blue"&gt;operator&lt;/span&gt;=(_In_ &lt;span style="color: blue"&gt;const &lt;/span&gt;CComPtr&amp;lt;Q&amp;gt;&amp;amp; lp) &lt;span style="color: blue"&gt;throw&lt;/span&gt;()
{
    &lt;span style="color: blue"&gt;if&lt;/span&gt;( !IsEqualObject(lp) )
    {
        &lt;span style="color: blue"&gt;return static_cast&lt;/span&gt;&amp;lt;T*&amp;gt;(AtlComQIPtrAssign((IUnknown**)&amp;amp;p, lp, &lt;span style="color: blue"&gt;__uuidof&lt;/span&gt;(T)));
    }
    &lt;span style="color: blue"&gt;return &lt;/span&gt;*&lt;span style="color: blue"&gt;this&lt;/span&gt;;
}&lt;/pre&gt;

&lt;p&gt;This templated operator allows for assignments between CComPtr instance no matter what the type is for the left and right side.&amp;#160; The effect is that instead of doing compile type C++ type conversion rules, it will instead rely on runtime COM polymorphic assignment rules via IUnknown::QueryInterface.&amp;#160; This moves assignment errors from compile time to runtime for unrelated interfaces.&amp;#160; &lt;/p&gt;

&lt;p&gt;This is further complicated because it only applies to assignment between CComPtr’s (and derived instances).&amp;#160; If the right hand side of the assignment is a non-smart pointer, compile time C++ conversions will apply.&amp;#160; To demonstrate …&lt;/p&gt;

&lt;pre class="code"&gt;        CComPtr&amp;lt;ISelectionTracking&amp;gt; spTracking;
        CComPtr&amp;lt;IOldTracking&amp;gt; spOld;
        ...
        spTracking = spOld;  &lt;span style="color: green"&gt;// Fails at runtime
        &lt;/span&gt;spTracking = (IOldTracking*)spOld;  &lt;span style="color: green"&gt;// Compilation Error
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;What surprised me though was talking to other developers about this issue.&amp;#160; Most agreed with me that this is a bug in CComPtr&amp;lt;T&amp;gt;, or at least very unexpected behavior.&amp;#160; A surprising number though did not expect this behavior but still considered it acceptable.&amp;#160; The difference comes down whether you view CComPtr&amp;lt;T&amp;gt; as a simple smart pointer responsible for AddRef/Release semantics or as that plus an enabler of QueryInterface style conversions.&amp;#160; I personally view CComPtr&amp;lt;T&amp;gt; as a simple smart pointer with know real understanding of QueryInterface style conversions and CComQIPtr&amp;lt;T&amp;gt; as a smart pointer which respects QueryInterface style conversions.&amp;#160;&amp;#160; As such this behavior is completely unexpected.&amp;#160; &lt;/p&gt;

&lt;p&gt;The fix in this case was pretty straight forward (use the new API) but I was still worried about how to prevent this type of problem in the future.&amp;#160; In particular how to get the failure back to a compile time error.&amp;#160; In the end we settled on using a stripped down version of CComPtr we already had in our code base going forward called CComPtrEx.&amp;#160; I’ve previously blogged about about the need for this type &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/22/multiple-paths-to-iunknown.aspx"&gt;here&lt;/a&gt;.&amp;#160; It’s different from CComPtr in the following ways&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Does not have the templated version of operator= and instead relies on compile time C++ conversions checks for assignment &lt;/li&gt;

  &lt;li&gt;Allows for interfaces which have multiple paths to IUnknown (can cause a compile time error in CComPtr). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also for purposes of rigor, we temporarily commented out the CComPtr&amp;lt;T&amp;gt; operator, recompiled our code base and verified no new errors popped up.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9916908" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Questions not to hinge a C++ interview on</title><link>http://blogs.msdn.com/jaredpar/archive/2009/04/21/questions-not-to-hinge-a-c-interview-on.aspx</link><pubDate>Tue, 21 Apr 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9557943</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>7</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9557943.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9557943</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9557943</wfw:comment><description>&lt;p&gt;People love to chat about how to conduct a C++ interview on &lt;a href="http://stackoverflow.com/search?q=c%2B%2B+interview"&gt;newsgroups&lt;/a&gt;.&amp;#160; Eventually these topics will shift into a discussion about what questions a candidate &lt;strong&gt;must&lt;/strong&gt; know in order for them to get a hire from a particular interview.&amp;#160; Unfortunately these questions tend to be items like the following.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;What happens when you delete NULL?&lt;/li&gt;    &lt;li&gt;Explain how exceptions affect constructor initialization.&lt;/li&gt;    &lt;li&gt;Which constructors are called for the following: SomeType a = SomeType(b); &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Sure these questions are valid parts of the language and knowing them is a plus and demonstrates a deal of mastery over the language.&amp;#160; But not knowing them should by no means by a deal breaker.&amp;#160; The goal of an interview is to spot good developers who will become a contributing member of the team.&amp;#160; Good developers are motivated and passionate problem solvers.&amp;#160; These questions are testing little more than memorization.&amp;#160; It’s easy to memorize rules after the fact.&amp;#160; It’s much more difficult to teach problem solving skills.&amp;#160; &lt;/p&gt;  &lt;p&gt;The problem with questions like the above is that a developer could be both passionate and competent in C++ and never have come across these rules.&amp;#160; C++ is an unbelievably huge language and can operate in many different ways where these type of situations simply don’t come up.&amp;#160; For instance, I’ve known several very good C++ developers that spent the majority of their time working with COM.&amp;#160; COM prefers HRESULTs to Exceptions and hence they never used exceptions in C++.&amp;#160; Once we introduced exceptions into the code base, it took about 30 minutes to explain the rules and we were done.&amp;#160; &lt;/p&gt;  &lt;p&gt;C++ interviews should focus on the qualities that make a good developer: problem solving and passion.&amp;#160; Of course a language based interview should certainly focus on the foundations of C/C+.&amp;#160; Items like pointers, stack vs. heap and the basics of memory management.&amp;#160; But don’t hinge the deal on little items that can be quickly taught.&amp;#160; Otherwise you’ll end up turning away good developers.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9557943" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Rant/default.aspx">Rant</category></item><item><title>Redefining Success</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/24/redefining-success.aspx</link><pubDate>Fri, 24 Oct 2008 15:00:41 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9010695</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9010695.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9010695</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9010695</wfw:comment><description>&lt;p&gt;Spent about an hour debugging a bit of code today.&amp;#160; I was attempting to read data from a particular source and kept getting back failure codes.&amp;#160; After some debugging I discovered the data didn't actually exist in the source I was reading from.&amp;#160; &lt;/p&gt;  &lt;p&gt;This put me back to investigating where I wrote the data out.&amp;#160; Restarted the scenario and verified that I actually called the data writing API and that it succeeded.&amp;#160; &lt;/p&gt;  &lt;p&gt;Now what?&amp;#160; Well the data clearly wasn't there so I concluded the data writing must be failing in some odd way.&amp;#160; I eventually found the data writing code and was horrified to find the following definition.&lt;/p&gt;  &lt;pre&gt;HRESULT WriteSomeData(...) {
  // We don't support data of this type
  return S_OK;
}&lt;/pre&gt;

&lt;p&gt;Personally I thought this warranted an error code (perhaps E_NOTIMPL).&amp;#160; But given the situation I must conclude the author successfully failed to write the data.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9010695" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Where does the * go?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/09/04/where-does-the-go.aspx</link><pubDate>Thu, 04 Sep 2008 15:00:04 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8922727</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8922727.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8922727</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8922727</wfw:comment><description>&lt;p&gt;This is a more amusing than functional debate I enter into from time to time.&amp;nbsp; On a line where you declare a pointer type in C++, where should the * go?&amp;nbsp; &lt;/p&gt; &lt;ol&gt; &lt;li&gt;Next to the type (i.e. Type* p1;) &lt;li&gt;Next to the variable name&amp;nbsp; (i.e. Type *p1;) &lt;li&gt;Who cares&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;For the moment lets ignore #3 (after all they don't care).&amp;nbsp; I'm a firm believer in #1.&amp;nbsp; After all * is a part of the type of the variable, not the name and therefore should be closer to the type.&amp;nbsp; &lt;/p&gt; &lt;p&gt;#2 believers disagree with this notion.&amp;nbsp; They believe the * is a part of the individual variable's type and not the actual type.&amp;nbsp; This is technically correct and can be demonstrated with the following code&lt;/p&gt; &lt;p&gt;&lt;/p&gt;&lt;pre&gt;  Type* p1, p2;
&lt;/pre&gt;
&lt;p&gt;The type of p2 is of course Type and not Type*. Therefore they argue, #2 is the superior way&lt;/p&gt;
&lt;p&gt;This is true but I'm also a firm believer in don't declare multiple variables in a single declaration statement while coding in C++ unless the type has a user defined constructor.&amp;nbsp; Namely to avoid situations just like this.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8922727" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Rant/default.aspx">Rant</category></item><item><title>Bit by void*</title><link>http://blogs.msdn.com/jaredpar/archive/2008/06/16/bit-by-void.aspx</link><pubDate>Mon, 16 Jun 2008 15:00:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8598714</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8598714.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8598714</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8598714</wfw:comment><description>&lt;p&gt;Recently I got bit by void* again because of another C++ quirk I didn't think through.&amp;#160; I had a class which wrapped a void* which could be one of many different structs.&amp;#160; The structs were POD and didn't have any shared functionality hence I didn't bother creating an inheritance hierarchy.&amp;#160; Unfortunately I defined the structs like so&lt;/p&gt;  &lt;pre&gt;class C1 {
  struct S1 {
    int field1;
    float field2;
  };
  struct S2 {
    char field1;
  };
  ~C1() {
    delete m_pData;
  }
  void* m_pData; // Can be S1,S2,etc ...
}&lt;/pre&gt;

&lt;p&gt;Unfortunately this &lt;strong&gt;appeared &lt;/strong&gt;to work fine for quite some time.&amp;#160; Then after a couple of days of bug fixes I ended up with a memory leak which I quickly tracked down to a leaked COM object.&amp;#160; Although C1 was at fault I didn't suspect any changes to this class because after all it was working fine for some time and all I did was add a new field to one of the structs.&amp;#160; If the structs were being successfully free'd before a new field shouldn't change anything.&lt;/p&gt;

&lt;p&gt;The field I added was of type CComPtr&amp;lt;T&amp;gt; which exposed a greater problem in my code.&amp;#160; Even though I properly delete the pointer in C1::~C1() I wasn't running the destructor on the pointed at data and instead I was just freeing the memory.&amp;#160; Until I added a field which had a non-trivial destructor this wasn't a problem (still a bug though).&amp;#160; &lt;/p&gt;

&lt;p&gt;Why did this happen?&amp;#160; By deleting a void* and expecting a destructor to run what I'm really doing is asking C++ to behave polymorphicly.&amp;#160; C++ as a rule won't behave this way unless it is specifically asked to with inheritance and virtual.&amp;#160;&amp;#160; In the case of void*, it just won't.&amp;#160; The fix is to actually implement an inheritance hierarchy which supports polymorphism.&lt;/p&gt;

&lt;p&gt;It's just another rule that I need to remember when coding C++.&amp;#160; &lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Deleting void* is dangerous, period. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unfortunately C++ has too many of these rules and not enough enforcement.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8598714" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>do {} while(0) what?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/21/do-while-0-what.aspx</link><pubDate>Wed, 21 May 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8525927</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8525927.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8525927</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8525927</wfw:comment><description>&lt;P&gt;A recent check in of mine raised a few eye brows during reviews.&amp;nbsp; I checked in a few macros which ended with/contained a "do{}while(0)" and people were curious as to why.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In my experience there are two main uses for it.&amp;nbsp; &lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Insert an empty statement with no runtime penalty &lt;/LI&gt;
&lt;LI&gt;Group a set of statements into a single statement followable by a semi-colon&lt;/LI&gt;
&lt;OL&gt;
&lt;LI&gt;do { Func1(); Func2() } while(0) &lt;/LI&gt;&lt;/OL&gt;&lt;/OL&gt;
&lt;P&gt;Macros are mutating little constructs which jump back and forth depending on the compile time options.&amp;nbsp; Many macros compile to different expressions based on the options and in some cases they compile to nothing.&amp;nbsp; This is where #1 really comes in hand.&amp;nbsp; Imagine you have the following code.&amp;nbsp; &lt;/P&gt;&lt;PRE&gt;  if(someCondition)
    MY_MACRO();&lt;/PRE&gt;
&lt;P&gt;Compiling MY_MACRO to nothing will cause at the least a compile time warning since you will have essentially if(someCondition);. Instead you can use the do{}while(0) trick.&lt;/P&gt;&lt;PRE&gt;#if CONST_1
#define MY_MACRO() Func1()
#else
#define MY_MACRO() do{}while(0)&lt;/PRE&gt;
&lt;P&gt;Another us is for stylistic reasons.&amp;nbsp; Some camps don't believe a ; should be used as a empty statement and use do{}while(0) instead.&amp;nbsp; I tend to agree.&amp;nbsp; Mainly because one of my early C professors had the same belief.&amp;nbsp; The habit stuck around.&amp;nbsp;&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Update: Changed incorrect use of word expression -&amp;gt; single statement &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8525927" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Saved by PowerShell</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/07/saved-by-powershell.aspx</link><pubDate>Wed, 07 May 2008 15:00:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8464494</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8464494.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8464494</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8464494</wfw:comment><description>&lt;p&gt;Recently I made a very large update to our code base.&amp;#160; Our code base lacked a standard way of guarding entry and exit points into the various components.&amp;#160; Having said guards is useful for error handling, tracing, reducing redundancy, etc ...&amp;#160; The edit standardized our entry points by adding start/end macros to our entry point functions.&amp;#160; In addition to other house keeping, the macros also created an HRESULT variable named &amp;quot;hr&amp;quot;.&amp;#160; Example below. &lt;/p&gt;  &lt;pre&gt;#define MY_ENTRY_GUARD() HRESULT hr
#define MY_ENTRY_EXIT() return hr&lt;/pre&gt;

&lt;p&gt;Ran suites, everything passed, checked in.&amp;#160; Then I got an email from another dev who spent some time tracking down a bug related to this check-in (sorry &lt;a href="http://blogs.msdn.com/calvin_hsia/"&gt;Calvin&lt;/a&gt;).&amp;#160; He discovered one scenario my fix did not take into account.&lt;/p&gt;

&lt;pre&gt;SomeMethod
{
  MY_ENTRY_GUARD();
  if ( somecondition ) {
    HRESULT hr = E_FAIL; // shadows the first hr
  }
  MY_ENTRY_EXIT(); // returns unmodified hr
}&lt;/pre&gt;

&lt;p&gt;The double declaration of the variable &amp;quot;hr&amp;quot; is not an error or even a warning in C++.&amp;#160; Instead the inner &amp;quot;hr&amp;quot; shadows the outer and hence the rest of the method doesn't update the &amp;quot;hr&amp;quot; which is actually returned.&amp;#160; So now I had to find every place in this change where a nested hr was declared.&amp;#160; Did I mention this edit was huge?&amp;#160; Going through by hand would not only be time consuming, it would also be very error prone.&amp;#160; &lt;/p&gt;

&lt;p&gt;At first I considered parsing out the C++ and doing basic brace matching to look for shadowing &amp;quot;hr&amp;quot; variables.&amp;#160; I ruled that out due to the amount of time I would need to invest in the script to take into account comments, string literals, etc ...&amp;#160; Really I didn't need brace matching, I really just needed to know when I entered and left a method.&amp;#160; Almost all C++ methods have their opening and closing braces on the first column.&amp;#160; Writing a script to detect this is trivial.&amp;#160; &lt;/p&gt;

&lt;p&gt;Script took about 5 minutes to write and 10 to run in the code base.&amp;#160; Saved me countless hours of error prone reviews.&amp;#160; Thank you PowerShell.&lt;/p&gt;

&lt;p&gt;Find-DoubleHr.ps1: &lt;/p&gt;

&lt;p&gt;param ( $argFileName = $(throw &amp;quot;Need a file name&amp;quot;) ) &lt;/p&gt;

&lt;p&gt;function Do-Work() { 
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; $i = 0 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; foreach ( $line in (gc $argFileName) )&amp;#160; { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new-tuple &amp;quot;Text&amp;quot;,$line,&amp;quot;LineNumber&amp;quot;,$i 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $i++ 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;} &lt;/p&gt;

&lt;p&gt;function Do-Parse() { 
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; begin { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $inMethod = $false 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenHresult = 0 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenMacro = 0 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; process { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $tuple = $_ 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if ( $inMethod ) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; switch -regex ($tuple.Text) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;^}&amp;quot; { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $inMethod = $false 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if ( ($seenHresult -ne 0 )-and ($seenMacro -ne 0) ) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Found a double {0},{1}&amp;quot; -f $seenHResult,$seenMacro 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenHresult = 0 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenMacro = 0 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; break 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;.*MY_ENTRY_GUARD.*&amp;quot; { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; write-debug (&amp;quot;Macro: {0} &amp;quot; -f $tuple.Text) 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenMacro = $tuple.LineNumber 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; break 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;HRESULT.*\Whr\W&amp;quot; { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; write-debug (&amp;quot;HResult: {0}&amp;quot; -f $tuple.Text) 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $seenHresult = $tuple.LineNumber 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; break 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; elseif ( $tuple.Text -match &amp;quot;^{&amp;quot; ) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; $inMethod = $true 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } 

  &lt;br /&gt;} &lt;/p&gt;

&lt;p&gt;&amp;quot;Processing $argFileName&amp;quot; 
  &lt;br /&gt;Do-Work | Do-Parse &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8464494" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category></item><item><title>C++ Programming Books</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/01/c-programming-books.aspx</link><pubDate>Thu, 01 May 2008 15:00:40 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8446549</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8446549.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8446549</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8446549</wfw:comment><description>&lt;p&gt;I was reading a post on Coding Horror the other day about programming books and how developers &lt;a href="http://www.codinghorror.com/blog/archives/001108.html"&gt;don't read enough of them.&lt;/a&gt;&amp;#160; I readily agree with the first two points in the article that 1) most programming books suck and 2) books are sold by weight not by volume.&amp;#160; Reading is an integral part of a developers life.&amp;#160; Blogs are a great source of info but books are a necessity as well.&amp;#160; &lt;/p&gt;  &lt;p&gt;In my experience, the hardest language to find a good book for is C++.&amp;#160; Far too many books and far too few which are worth reading.&amp;#160; Here are my favorite which 1) don't suck and 2) don't weigh a ton but have a enormous amount of information.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Herb Sutter: &lt;/li&gt;    &lt;ol&gt;     &lt;li&gt;&lt;a href="http://www.amazon.com/Exceptional-Engineering-Programming-Solutions-Depth/dp/0201615622"&gt;Exceptional C++&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.amazon.com/More-Exceptional-Engineering-Programming-Depth/dp/020170434X/ref=pd_bxgy_b_img_b/105-5993487-4416400"&gt;More Exceptional C++&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.amazon.com/Exceptional-C%2B%2B-Style-Engineering-Depth/dp/0201760428/ref=sr_1_3?ie=UTF8&amp;amp;s=books&amp;amp;qid=1209624394&amp;amp;sr=1-3"&gt;Exceptional C++ Style&lt;/a&gt;&lt;/li&gt;   &lt;/ol&gt;    &lt;li&gt;Scott Meyers&lt;/li&gt;    &lt;ol&gt;     &lt;li&gt;&lt;a href="http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Depth/dp/0321227255"&gt;Effective C++&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.amazon.com/More-Effective-Addison-Wesley-Professional-Computing/dp/020163371X/ref=pd_bxgy_b_img_b"&gt;More Effective C++&lt;/a&gt;&lt;/li&gt;   &lt;/ol&gt; &lt;/ol&gt;  &lt;p&gt;Others may disagree but I classify the Scott Meyer books as being good for developers looking to break into the intermediate level.&amp;#160; Herb Sutter is great for developers looking to cross from a intermediate to efficient level in C++. &lt;/p&gt;  &lt;p&gt;For developers who think they're ready to cross into the expert realm I highly recommend &amp;quot;&lt;a href="http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Depth/dp/0321227255"&gt;C++ Template Metaprogramming&lt;/a&gt;.&amp;quot;&amp;#160; It should convince you that being an expert it C++ is near impossible :)&lt;/p&gt;  &lt;p&gt;IMHO, the first two Herb Sutter books I listed should be required reading for anyone doing C++ software development.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8446549" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category></item><item><title>Gotcha: CComAutoCriticalSection and copy constructors</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/24/gotcha-ccomautocriticalsection-and-copy-constructors.aspx</link><pubDate>Thu, 24 Apr 2008 15:00:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8417161</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8417161.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8417161</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8417161</wfw:comment><description>&lt;p&gt;While investigating a crash during a suite run I found the stack walk included the destructor for a &lt;a href="http://msdn2.microsoft.com/en-us/library/50yhb8t7.aspx"&gt;CComAutoCriticalSection&lt;/a&gt;.&amp;nbsp; This is a fairly reliable class so I immediately suspected my code.&amp;nbsp; I did a couple of quick checks for a double free and didn't find any.&amp;nbsp; Then I looked a little closer at CComAutoCriticalSection and spotted that it doesn't redefine the standard copy and operator= constructor.&lt;/p&gt; &lt;p&gt;This is a red flag for any class that implements RAII.&amp;nbsp; C++ will automatically define a copy/operator= for your clasess which will amount to a memcpy.&amp;nbsp; This means copies of two objects will be managing the same resource.&amp;nbsp; Once the second one is destroyed it will result in a double free and hopefully a crash.&amp;nbsp; &lt;/p&gt; &lt;p&gt;I walked the hierarchy and discovered that none of the base classes redefined these methods either.&amp;nbsp; After that it only took a few minutes to discover the bug.&amp;nbsp; I attempt to pass the object by reference but instead ended up passing it by value.&amp;nbsp; &lt;/p&gt; &lt;p&gt;To ensure I didn't miss any other cases of this, I added the following definition to my code base and moved all instances of CComAutoCriticalSection to point to this version.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; SafeCriticalSection : &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; CComAutoCriticalSection
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    SafeCriticalSection() {}
&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    SafeCriticalSection(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; SafeCriticalSection&amp;amp;);
    SafeCriticalSection&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; SafeCriticalSection&amp;amp;);
};&lt;/pre&gt;It should be standard practice to define all 3 of the above methods on any class which has RAII semantics.&amp;nbsp; This is not necessary if all of the members are copy safe (CComPtr&amp;lt;&amp;gt; for example). &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8417161" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Thread Local Storage template</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/21/thread-local-storage-template.aspx</link><pubDate>Mon, 21 Apr 2008 20:52:03 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8415085</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8415085.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8415085</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8415085</wfw:comment><description>&lt;p&gt;Thread local storage is another method of synchronization between threads.&amp;nbsp; It is different that most synchronization cases because instead of sharing state between threads it enables developers to have independent, thread specific pieces of data which have a similar or common purpose.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The uses of thread local storage (TLS) vary greatly but is a very powerful and lightweight method for storing data.&amp;nbsp; TLS can easily be envisioned as a giant void* array for every thread.&amp;nbsp; The entry point, TlsAlloc, provides an index into this array and allows the storage of arbitrary data [1].&lt;/p&gt; &lt;p&gt;TLS is particularly useful for storing state information.&amp;nbsp; For example, one of my components lives in a highly multi-threaded environment.&amp;nbsp; Each thread serves essentially the same purpose and has the same states and state transition semantics.&amp;nbsp; Like any good paranoid programmer I wanted to add contracts to check my state transitions and semantics.&amp;nbsp; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Contract.VerifyState(ExpectedState, ???CurrentState)&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The question is where to store the state information for a thread?&amp;nbsp; A global state variable won't suffice because there are N threads.&amp;nbsp; A global array of state information also has it's share of problems: synchronization, determining an index, lifetime. &lt;/p&gt; &lt;p&gt;TLS is ideally suited to this scenario.&amp;nbsp; Each thread has an independent but similar concept of state.&amp;nbsp; In my initialization code I allocate an TLS index and now I have a place to store my state.&amp;nbsp; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Contract.VerifyState(ExpectedState, *TlsGetValue(g_stateTlsIndex)&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The next question is how to manage the lifetime?&amp;nbsp; TLS provides a void* and the caller must manage the lifetime of the allocated memory.&amp;nbsp;&amp;nbsp; Since this is thread specific the ideal place is to manage the memory in the thread startup proc.&amp;nbsp; However I don't own the creation of the thread, my component is called on a number of threads so this won't work.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The solution is to use the stack.&amp;nbsp; The initial return for TlsGetValue is NULL.&amp;nbsp; If this situation is detected then the current stack frame is set to own the memory for the slot.&amp;nbsp; Further accesses to the value do not own the memory and simply access it.&amp;nbsp; The semantics are straight forward but annoying to constantly rewrite, so naturally write a template :)&lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
    &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; TlsValue
    {
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
        TlsValue(DWORD index, &lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; T&amp;amp; defaultValue=T()) :
            m_pValue(NULL),
            m_index(index),
            m_owns(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;)
        {
            m_pValue = &lt;span style="color: rgb(0,0,255)"&gt;reinterpret_cast&lt;/span&gt;&amp;lt;T*&amp;gt;(::TlsGetValue(m_index));
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; ( !m_pValue )
            {
                m_pValue = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; T(defaultValue);
                m_owns = &lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;;
                ::TlsSetValue(m_index, m_pValue);
            }
        }
        ~TlsValue()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; ( m_owns )
            {
                ::TlsSetValue(m_index, NULL);
                &lt;span style="color: rgb(0,0,255)"&gt;delete&lt;/span&gt; m_pValue;
            }
        }

        T* Value() &lt;span style="color: rgb(0,0,255)"&gt;const
&lt;/span&gt;        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_pValue;
        }

    &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
        &lt;span style="color: rgb(0,128,0)"&gt;// Do not auto generate
&lt;/span&gt;        TlsValue();
        TlsValue(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; TlsValue&amp;lt;T&amp;gt;&amp;amp;);
        TlsValue&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; TlsValue&amp;lt;T&amp;gt;&amp;amp;);

        T* m_pValue;
        DWORD m_index;
        &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; m_owns;
    };
&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In addition to this blog post, I added a working sample to &lt;a title="http://code.msdn.microsoft.com/TlsValue" href="http://code.msdn.microsoft.com/TlsValue"&gt;http://code.msdn.microsoft.com/TlsValue&lt;/a&gt;.&amp;nbsp; This is my first attempt at posting a sample on &lt;a href="http://code.msdn.com"&gt;http://code.msdn.com&lt;/a&gt; so please provide any and all feedback on the data.&lt;/p&gt;
&lt;p&gt;[1] This is similar to data marked with the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx"&gt;ThreadStatic attribute&lt;/a&gt; in managed code without all of the slot messiness and with the added benefit of strong typing.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8415085" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category></item><item><title>Gotcha: CComPtrBase&lt;T&gt; assignment</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/08/gotcha-ccomptrbase-t-assignment.aspx</link><pubDate>Tue, 08 Apr 2008 18:44:16 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8352116</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8352116.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8352116</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8352116</wfw:comment><description>&lt;p&gt;Today what started out as a crash due to a pure virtual call turned into finding a gotcha in CComPtrBase&amp;lt;T&amp;gt;.&amp;nbsp; Essentially the code in question boiled down to the following.&amp;nbsp; Can you spot the problem?&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; GetAStudent(CComPtrBase&amp;lt;T&amp;gt; &amp;amp;spStudent)
{
    CComPtr&amp;lt;Student&amp;gt; spLocal;
    &lt;span style="color: rgb(0,128,0)"&gt;// Do some operation to get a student
&lt;/span&gt;    spLocal = spStudent;
}&lt;/pre&gt;
&lt;p&gt;The problem isn't apparent until you look at the definition for CComPtrBase&amp;lt;T&amp;gt;::operater =.&amp;nbsp; See the problem?&amp;nbsp; Basically CComPtrBase&amp;lt;T&amp;gt;::operator= isn't explicitly defined.&amp;nbsp; This means that C++ will automatically implement &lt;a href="http://msdn2.microsoft.com/en-us/library/x0c54csc(VS.71).aspx"&gt;memberwise assignment.&lt;/a&gt;&amp;nbsp; The RHS of the operator= will be a "const CComPtrBase&amp;lt;T&amp;gt;&amp;amp;".&amp;nbsp; &lt;/p&gt;
&lt;p&gt;CComPtr&amp;lt;T&amp;gt; derives from CComPtrBase&amp;lt;T&amp;gt; therefore it satisfies this and a memberwise assignment will occur.&amp;nbsp; We now have two smart pointers on the same value.&amp;nbsp; However the second smart pointer, CComPtrBase&amp;lt;T&amp;gt;, did not perform an AddRef.&amp;nbsp; So when both objects are destroyed there will be an extra Release and hopefully a crash.&lt;/p&gt;
&lt;p&gt;The fix? &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use CComPtr&amp;lt;T&amp;gt; or CComPtrEx&amp;lt;T&amp;gt; instead of CComPtrBase&amp;lt;T&amp;gt;&lt;/li&gt;
&lt;li&gt;Less Optimal: call AddRef() on spLocal.&amp;nbsp;&amp;nbsp; &lt;/li&gt;&lt;/ol&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8352116" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Reference values in C++</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/03/reference-values-in-c.aspx</link><pubDate>Thu, 03 Apr 2008 17:24:54 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8345947</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8345947.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8345947</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8345947</wfw:comment><description>&lt;p&gt;Reference values are a powerful feature of C++ but I find they have one significant detractor.&amp;nbsp; A developer can not look at an API call and determine if a parameter is being passed by reference or value (VB has the same problem).&amp;nbsp; &lt;/p&gt; &lt;p&gt;IMHO this is one item that C# got 100% correct.&amp;nbsp; In C# developers must say a value is out/ref or a compile error results.&amp;nbsp; Forcing both the API declaration and usage to specify the reference semantics makes code much more understandable.&amp;nbsp; When you look at an API call there is absolutely no question about the byref/byval/out semantics of a parameter.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Internally I've met people who are hesitant to use reference parameters in C++ because of the ambiguity.&amp;nbsp; Not making it declarative in both places meant unexpected behavior could occur in a number of scenarios.&amp;nbsp; I agree with this statement.&amp;nbsp; &lt;/p&gt; &lt;p&gt;But hey we're talking about C++ here.&amp;nbsp; Any C++ problem can be fixed with some macros and a template right?&amp;nbsp; I thought about this over the weekend and came up with a quick sample.&amp;nbsp; Note, I haven't extensively tested this sample yet so there may be bugs.&amp;nbsp; However it gets the base cases right.&lt;/p&gt; &lt;p&gt;The goal of this API is to allow API authors to force developers to be explicit about their ByRef semantics.&amp;nbsp; It will prevent developers from silently passing a value by ref and hence getting unexpected behavior.&amp;nbsp; Failure to do so will result in a compile time error.&amp;nbsp; Also there is a minor bit of indirection overhead for debug mode but in retail this will compile out to normal code.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;#ifdef&lt;/span&gt; DEBUG

&lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; ByRefType
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    &lt;span style="color: rgb(0,0,255)"&gt;explicit&lt;/span&gt; ByRefType(T&amp;amp; arg) : m_ref(arg)
    {
    }

    &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt; T&amp;amp;() &lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; 
    {
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_ref;
    }

    ByRefType&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; T&amp;amp; value)
    {
        m_ref = value;
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; *&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;;
    }

&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    ByRefType();

    &lt;span style="color: rgb(0,0,255)"&gt;mutable&lt;/span&gt; T&amp;amp; m_ref;
};

&lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
ByRefType&amp;lt;T&amp;gt; MakeByRefType(T&amp;amp; expr)
{
    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; ByRefType&amp;lt;T&amp;gt;(expr);
}

&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; ByRef(expr) MakeByRefType(expr)
&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; ByRefParam(type) ByRefType&amp;lt;type&amp;gt; 

&lt;span style="color: rgb(0,0,255)"&gt;#else

&lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;#define ByRef(expr) expr
#define ByRefParam(type) type&amp;amp;

&lt;/span&gt;&lt;span style="color: rgb(0,0,255)"&gt;#endif&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;All well and good.&amp;nbsp; Now we can attribute byref paramaters with ByRefParam() and force callers to tag it as a ByRef argument.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; SimpleByRef(ByRefParam(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;) i, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; newValue)
{
    i = newValue;
}

&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Test()
{
    &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; i1;
    SimpleByRef(ByRef(i1), 5);
    SimpleByRef(i1, 6);     &lt;span style="color: rgb(0,128,0)"&gt;// Compiler Error!!!
&lt;/span&gt;}&lt;/pre&gt;As said before, this is an initial implementation and I expect updates as I use this in code and find bugs.&amp;nbsp; Please post back with any you find.&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8345947" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>API Problems: CComObject::CreateInstance</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/28/api-problems-ccomobject-createinstance.aspx</link><pubDate>Sat, 29 Mar 2008 02:38:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8342588</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8342588.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8342588</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8342588</wfw:comment><description>&lt;P&gt;&lt;A href="http://msdn2.microsoft.com/en-us/library/9e31say1.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/9e31say1.aspx"&gt;CComObject::CreateInstance&lt;/A&gt; is a light weight method for creating instances of COM objects in your code.&amp;nbsp; Unfortunately the design of the API makes it easy to introduce subtle errors into your code.&amp;nbsp; The two problems are it encourages manually ref counting and the object initially has a ref count of 0.&amp;nbsp; This means you must remember to AddRef before calling any other function. Neither of these ideas in themselves are bad but it leads to tedious, repetitive code that is too often done incorrectly.&lt;/P&gt;
&lt;P&gt;Below is a typical example I see in code. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod()
{
    CComObject&amp;lt;Student&amp;gt; *pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CComObject&amp;lt;Student&amp;gt;::CreateInstance(&amp;amp;pStudent)) )
    {
        pStudent-&amp;gt;AddRef();
        VerifyStudent(pStudent);
        pStudent-&amp;gt;Release();
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;As a result of the manual ref counting, this code is not exception safe.&amp;nbsp; If VerifyStudent or any API it calls throws, an instance of Student will be leaked.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The second problem I often see in code is the placement of the VerifyStudent function.&amp;nbsp; Occasionally I see methods like VerifyStudent called before the AddRef.&amp;nbsp; If you see this in your code immediately file a bug.&amp;nbsp; The problem is the ref count is 0 before you call AddRef.&amp;nbsp; It COM it should always be legal to AddRef/Release a COM object passed into your function.&amp;nbsp; In this case while legal it will destroy the instance of Student.&amp;nbsp; What's even worse is this bug can show up years after you code.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Real world example.&amp;nbsp; I created a class to wrap a couple of operations.&amp;nbsp; One of it's members was Student and as such I wrapped it in a CComPtr&amp;lt;&amp;gt; for ease of use.&amp;nbsp; Fired up the program and everything crashed.&amp;nbsp; Turns out an instance of Student was passed to a function that eventually created an instance of my object before AddRef was called (essentially move VerifyStudent up one line).&amp;nbsp; As soon as my new object died CComPtr&amp;lt;&amp;gt; called Release, moved the RefCount to 0 and destroyed the object.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Writing the correct code is repetitive and begs for a wrapper function.&amp;nbsp; Enter CreateWithRef&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;template&lt;/SPAN&gt; &amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; T&amp;gt;
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;static&lt;/SPAN&gt; 
HRESULT CreateWithRef(T** ppObject)
{
    CComObject&amp;lt;T&amp;gt; *pObject;
    HRESULT hr = CComObject&amp;lt;T&amp;gt;::CreateInstance(&amp;amp;pObject);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(hr) )
    {
        pObject-&amp;gt;AddRef();
        *ppObject = pObject;
    }

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; hr; 
}

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod2()
{
    CComPtr&amp;lt;Student&amp;gt; pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CreateWithRef(&amp;amp;pStudent)) )
    {
        VerifyStudent(pStudent);
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;As you can see, using this function takes less typing that a normal CreateInstance due to using type inference.&amp;nbsp; It's also exception safer since the resource is managed.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;This API still has one flaw.&amp;nbsp; It allows people to pass in a raw pointer and hence violate exception safety.&amp;nbsp; It could be improved by forcing a caller to pass in a class which supports &lt;A href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" mce_href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization"&gt;RAII&lt;/A&gt;.&amp;nbsp; In this case a good choice is CComPtrBase&amp;lt;&amp;gt;.&amp;nbsp; I tend to prefer this design because it forces the caller to use safer code.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;template&lt;/SPAN&gt; &amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; T&amp;gt;
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;static&lt;/SPAN&gt; 
HRESULT CreateWithRef2(CComPtrBase&amp;lt;T&amp;gt;&amp;amp; spPointer)
{
    CComObject&amp;lt;T&amp;gt; *pObject;
    HRESULT hr = CComObject&amp;lt;T&amp;gt;::CreateInstance(&amp;amp;pObject);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(hr) )
    {
        pObject-&amp;gt;AddRef();
        spPointer.Attach(pObject);
    }

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; hr; 
}

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod3()
{
    CComPtr&amp;lt;Student&amp;gt; pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CreateWithRef2(pStudent)) )
    {
        VerifyStudent(pStudent);
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8342588" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Multiple paths to IUnknown</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/22/multiple-paths-to-iunknown.aspx</link><pubDate>Fri, 22 Feb 2008 09:21:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7845303</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7845303.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7845303</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7845303</wfw:comment><description>&lt;P&gt;ATL has a lot of great tools for COM programming and &lt;A href="http://msdn2.microsoft.com/en-us/library/ezzw7k98(VS.80).aspx" mce_href="http://msdn2.microsoft.com/en-us/library/ezzw7k98(VS.80).aspx"&gt;CComPtr&lt;/A&gt; is a good example.&amp;nbsp; It's a smart pointer class which manages the reference count of an underlying COM object. &lt;/P&gt;
&lt;P&gt;One of it's limitations though is it will only work properly when the inheritance chain for a class has only one path to IUnknown.&amp;nbsp; If it has more than one path, the following error will be issued when you attempt to assign a value of type T to the CComPtr.&lt;/P&gt;
&lt;P&gt;error C2594: 'argument' : ambiguous conversions from 'SomeClass *' to 'IUnknown *'&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The reason behind this is the operator= for CComPtr uses &lt;A href="http://msdn2.microsoft.com/en-us/library/40d27a83(vs.71).aspx" mce_href="http://msdn2.microsoft.com/en-us/library/40d27a83(vs.71).aspx"&gt;AtlComPtrAssign&lt;/A&gt; to change the references.&amp;nbsp; The right hand side of the assignment is passed to this function as IUnknown.&amp;nbsp; Since there are multiple paths to IUnknown the C++ compiler cannot implicitly perform the cast and issues the above error.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;I most frequently encounter this error in larger code bases with older classes.&amp;nbsp; New functionality is needed so I add a new interface and end up with a lot of C2594 errors.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;To work around this I defined a new CComPtr class named CComPtrEx which inherits from CComPtr base.&amp;nbsp; It defines the same operators as CComPtr but uses a Copy Constructor and Swap to perform the = which gets around the multiple paths to IUnknown.&amp;nbsp; The rest of the functions are identical to CComPtr.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;template&lt;/SPAN&gt; &amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; T&amp;gt;
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; CComPtrEx : &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; CComPtrBase&amp;lt;T&amp;gt;
{
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt;:
    CComPtrEx() &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;()
    {
    }
    CComPtrEx(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; nNull) &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;() :
        CComPtrBase&amp;lt;T&amp;gt;(nNull)
    {
    }
    CComPtrEx(T* lp) &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;() :
        CComPtrBase&amp;lt;T&amp;gt;(lp)
    {
    }
    CComPtrEx(_In_ &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;const&lt;/SPAN&gt; CComPtrEx&amp;lt;T&amp;gt;&amp;amp; lp) &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;() :
        CComPtrBase&amp;lt;T&amp;gt;(lp.p)
    {
    }

    T* &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;operator&lt;/SPAN&gt;=(_In_opt_ T* lp) &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;()
    {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt;(*&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;!=lp)
        {
            CComPtrEx&amp;lt;T&amp;gt; sp(lp);
            Swap(&amp;amp;p, &amp;amp;sp.p);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; *&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;;
    }

    T* &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;operator&lt;/SPAN&gt;=(_In_ &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;const&lt;/SPAN&gt; CComPtrEx&amp;lt;T&amp;gt;&amp;amp; lp) &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt;()
    {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt;(*&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;!=lp)
        {
            CComPtrEx&amp;lt;T&amp;gt; sp(lp);
            Swap(&amp;amp;p, &amp;amp;sp.p);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; *&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;;
    }
};&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7845303" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category></item><item><title>Mixing SEH and C++ Exceptions</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/11/mixing-seh-and-c-exceptions.aspx</link><pubDate>Sat, 12 Jan 2008 01:18:01 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7080240</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7080240.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7080240</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7080240</wfw:comment><description>&lt;p&gt;Recently I had a half day adventure trying to catch a SafeIntException in code I was writing.&amp;nbsp; The particular function involved a bit of math with user controlled values.&amp;nbsp; Writing a bunch of IfFailGo's with several TryAdd style API's was getting tiresome so I decided to just use SafeInt, catch an overflow and return a failure code.&amp;nbsp; &lt;/p&gt; &lt;p&gt;After recompiling the code I got an error because I hadn't enabled C++ exception handling in the project.&amp;nbsp; Fix to support synchronous exceptions (/Ehs), recompile.&amp;nbsp; Now I get a different error because a portion of the code base is using SEH exception handling.&amp;nbsp; No problem, changed the project to support asynchronous exception handling as well (/Eha).&amp;nbsp; And yet again another error, the compiler now said that I could not use variables with a destructor in the same method that had an SEH try block.&amp;nbsp; &lt;/p&gt; &lt;p&gt;This put me in a bit of a corner.&amp;nbsp; The code base is littered with SEH exception handling and much of it is perfectly valid.&amp;nbsp; Luckily the number of places using both SEH and destructors was fairly limited.&amp;nbsp; What I needed was a way to unify the exception handling to allow me to use destructors in the same place as SEH exceptions.&lt;/p&gt; &lt;p&gt;With /Eha there is a built-in way.&amp;nbsp; You can catch all SEH exceptions using the C++ syntax "catch (...)".&amp;nbsp; However this method is limiting because you cannot access the SEH exception code and you get notified after the stack unwind occurs.&amp;nbsp; In SEH an exception filter is run before a stack unwind occurs which makes it infinitely easier to track down your bugs as you can just look down the stack trace and see the line of code that faulted.&lt;/p&gt; &lt;p&gt;After a bit of research I found a solution.&amp;nbsp; I'm chose to blog about it because many of the questions I needed answers for were either 1) undocumented or 2) documented to vaguely.&amp;nbsp; In the end I setup some experiment projects to confirm the behaviors I expected.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The magic function I was looking for was &lt;a href="http://msdn2.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx"&gt;_set_se_translator&lt;/a&gt;.&amp;nbsp; It takes a function pointer as an argument and returns the previous value.&amp;nbsp; The documentation states that when a C/SEH exception is raised this function pointer is called once per function that has a C++ try block.&amp;nbsp; It can be used to throw a C++ exception in place of a SEH exception.&amp;nbsp; So you can now translate a SEH exception into a C++ one.&lt;/p&gt; &lt;p&gt;What the documentation didn't explain (and I was very curious about) is how this interweaves with existing SEH __try/__except/__finally blocks.&amp;nbsp; After some experimentation I discovered that it works extremely well.&amp;nbsp; SEH exceptions occur in two phases&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Process the exception filters until either EXCEPTION_EXECUTE_HANDLER or EXCEPTION_CONTINUE_EXECUTION is returned&lt;/li&gt; &lt;li&gt;If EXECEPTION_EXECUTE_HANDLER is returned the stack is unwound to the point of the exception handler block and it is then executed.&amp;nbsp; &lt;/li&gt;&lt;/ol&gt; &lt;p&gt;The value passed to &lt;a href="http://msdn2.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx"&gt;_set_se_translator&lt;/a&gt; participates in phase 1 of the process.&amp;nbsp; As the CRT is looking down the stack for a SEH exception filter, if it finds a C++ try block it will also process the last value passed to &lt;a href="http://msdn2.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx"&gt;_set_se_translator&lt;/a&gt; and allow it to throw a C++ exception.&amp;nbsp; If an exception is thrown the stack is unwound to that point and then the exception is thrown.&amp;nbsp; This means that if you call into other code which uses traditional SEH handlers they will operate just as they did before you started using &lt;a href="http://msdn2.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx"&gt;_set_se_translator&lt;/a&gt;.&amp;nbsp; Most importantly __finally blocks will run and __except blocks above you in the stack still process and can handle SEH exceptions.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The next step was to write an easy to use wrapper for this functionality.&amp;nbsp; I used two classes to implement this approach.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The first class is designed to properly install a translator at a given point in the stack and ensure that it is reset to the previous value when that stack frame is popped off.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;extern&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; SehTranslatorFunction(&lt;span style="color: rgb(0,0,255)"&gt;unsigned&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;struct&lt;/span&gt; _EXCEPTION_POINTERS*);

&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; SehGuard
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    SehGuard()
    {
        m_prev = _set_se_translator(SehTranslatorFunction);
    }

    ~SehGuard()
    {
        _set_se_translator(m_prev);
    }

&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    _se_translator_function m_prev;
};&lt;/pre&gt;
&lt;p&gt;The second part is to actually throw an exception inside of SehTranslatorFunction.&amp;nbsp; Also to add an assert so that when an SEH exception is produced I can break at the point of failure (as opposed to in the catch block where the stack will be unwound. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; SehException
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    SehException(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; code) : m_code(code) { }
&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    &lt;span style="color: rgb(0,0,255)"&gt;unsigned&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_code;
};&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; SehTranslatorFunction(&lt;span style="color: rgb(0,0,255)"&gt;unsigned&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; code, &lt;span style="color: rgb(0,0,255)"&gt;struct&lt;/span&gt; _EXCEPTION_POINTERS*)
{
    MyAssertFunction(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;,&lt;span style="color: rgb(163,21,21)"&gt;"Caught an SEH exception"&lt;/span&gt;);
    &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; SehException(code);
}&lt;/pre&gt;Now whenever I hit a point where I want to guard against SEH exceptions, I just put and instance of SehGuard on the stack and catch SehException instances.&amp;nbsp; No traditional SEH needed.&amp;nbsp; &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7080240" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/SEH/default.aspx">SEH</category></item></channel></rss>