Avoid Memory Corruption when Assigning a CComBSTR to a CComVariant's bstrVal Member


Although the CComBSTR = operator is overloaded to make a copy of the string, this is not the case when assigning a CComVariant's bstrVal member to a CComBSTR. In this case, you need to make an explicit copy:

CComVariant bstrTarget;
CComBSTR strSource("test");

// Use CComBSTR::Copy to make a copy
// of the source string.
bstrTarget.bstrVal = strSource.Copy();
If you don't make a copy of the source string, it will wind up being freed twice—once by the CComVariant's destructor, and once by the original CComBSTR's destructor. 

你可能感兴趣的:(Avoid Memory Corruption when Assigning a CComBSTR to a CComVariant's bstrVal Member)