Minimal code reproducing the problem:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
CComBSTR ccbTest( L"foo" );
const wchar_t * pTest = ccbTest ? ccbTest : L"null string";
return 0;
}
The compiler uses a temporary CComBSTR
when it wants to store a pointer in pTest
. It then uses the BSTR
conversion available in the CCcomBSTR
class, with the temporary, and stores the pointer in pTest
. Then the temporary is destroyed, and I am left with a dangling pointer in pTest
.
The fix is to cast the CComBSTR
:
const wchar_t * pTest = ccbTest ? static_cast<BSTR>( ccbTest ) : L"null string";
I don't understand why the fix is necessary. I thought that the compiler would just try to convert to BSTR
all by itself. Why a temporary?