title: How to clean up _variant_t
body: <p>My leak checker tells me there is 2nd chance exception in this function.</p>
  
  <pre><code>BOOL CADORecordset::SetFieldValue(LPCTSTR lpFieldName, CString strValue)
  {
      _variant_t vtFld;
  
      if(!strValue.IsEmpty())
          vtFld.vt = VT_BSTR;
      else
          vtFld.vt = VT_NULL;
  
      vtFld.bstrVal = strValue.AllocSysString();
  
      BOOL bret = PutFieldValue(lpFieldName, vtFld);
      SysFreeString(vtFld.bstrVal);
  
      return bret;
  }
  </code></pre>
  
  <p>Now <code>_variant_t</code> has a type BSTR member (<code>bstrVal</code>). We <a href="https://msdn.microsoft.com/en-us/library/aa314307(v=vs.60).aspx" rel="nofollow">know</a> that BSTR needs to be de-allocated using <code>SystemFreeString()</code> which is what is done in the code above but since this BSTR is member of <code>_variant_t</code> who has its own destructor which cleans up, who should really clean up the <code>bstrVal</code> member in this case? </p>
  
  <pre><code>inline _variant_t::~_variant_t() throw()
  {
      ::VariantClear(this);
  }
  </code></pre>
  
  <p>It appears to me that this tries to clean up the memory again which is already cleaned up by <code>SysFreeString()</code> causing the exception? The <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms221165(v=vs.85).aspx" rel="nofollow">documentation</a> says it clears the variant but it is not clear what exactly it clears, does it free up the <code>bstrVal</code> as well?</p>
  
  <p>If I remove the call <code>SysFreeString(vtFld.bstrVal);</code> this does remove the 2nd chance exception but I really want to know that's the right thing to do because the documentation doesn't give enough confidence.</p>