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

来源:互联网 发布:linux vi 命令没用 编辑:程序博客网 时间:2024/06/04 18:37

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. 
原创粉丝点击