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?
The temporary exist for the same reasons this question does.
And as stated in one of its answer:
Since your
L"null string"
is a temporary of a different type thanCComBSTR
the whole result of the ternary is a value type which means the result is copied in a temporary.If you try:
There is no more temporary.