I believe the following causes a memory access violation error as the false parameter (fcopy) causes the memory to be released for the CComBSTR:
CComBSTR myCComBSTR;
string strMyCComBSTR = string(_bstr_t(myCComBSTR, false));
However, I’m not quite sure why this is as the MSDN documentation says the following about fcopy:
If false, the bstr argument is
attached to the new object without
making a copy by calling
SysAllocString.
My question is:
- Am I right in saying that this is a problem
- If so – why?
Thanks
Yes, this is a problem – both
myCComBSTRand the temporary will try to free the string since they both will think they own it.You see,
fcopyhaving value offalsemeans “please don’t duplicate the string body, just attach to the body I give you”. When the first line completes you havemyCComBSTRowning the string buffer and when the temporary object on the second line is created it also takes ownership of the same string buffer because offcopybeingfalse. Then the temporary is destroyed and frees the string buffer. LatermyCComBSTRwill be destroyed and will try to free the same string buffer again – you run into so-called double free which induces undefined behavior.