title: C++ leak with VARIANT / bstrVal code
body: <p>A leak checker tells me that I have a memory leak on memory that is allocated in the following code:</p>
  
  <pre><code>// Get the value from the object as a variant.
  VARIANT vVal;
  VariantInit ( &amp;vVal );
  hres = clsObj-&gt;Get ( fieldName.c_str(), 0, &amp;vVal, 0, 0 );
  if ( FAILED ( hres ) )
  {
      (... various cleanup / throw stuff ...)
  }
  
  // And get it as a wstring.
  wstring val ( vVal.bstrVal );
  
  (... do some standard, non-memory leaking stuff with the wstring ...)    
  
  // Clean up.
  VariantClear ( &amp;vVal );
  </code></pre>
  
  <p>The "clsObj" in there is a IWbemClassObject, which is a Microsoft interface for WMI stuff.</p>
  
  <p>The specific line that allocates the leaked memory is the "clsObj->Get" line.  The leak checker then reports more specific code for the leak itself (i.e. further in the stack trace at the time of the allocation of the leaked memory) for which I don't have the source code:</p>
  
  <pre><code>(ole32): (filename not available): CoRevokeMallocSpy    
  (OLEAUT32): (filename not available): GetErrorInfo  
  (OLEAUT32): (filename not available): SysAllocStringLen 
  (OLEAUT32): (filename not available): SysAllocString    
  (wbemcomn): (filename not available): CVar::SetBSTR 
  (wbemcomn): (filename not available): CVar::FillVariant 
  (fastprox): (filename not available): CWbemObject::Get  
  </code></pre>
  
  <p>So the underlying BSTR in the VARIANT vVal is being leaked, it seems.  But I'm doing a VariantClear... do I have to do something else?</p>
  
  <p>Perhaps I'm leaking it in the wstring constructor? But if so, I don't understand.  I thought bstrVal essentially just boils down to a char pointer (or wchar or whatever); the wstring constructor should just copy from that address as if it were any other pointer, right? </p>
  
  <p>It's not like the wstring constructor takes over responsibility for clearing up the memory that's originally pointed to by vVal.bstrVal, as if it were doing a Detach() on some reference counted COM object, is it?</p>
  
  <p>In case it matters, this is in Visual C++ 6.</p>