Why does the compiler use a temporary variable?

Minimum 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 save a pointer to pTest . It then uses the BSTR transform, available in the CCcomBSTR class, with a temporary one and stores the pointer in pTest . Then the temporary is destroyed and I remain with the pTest pointer in pTest .

The fix is ​​to draw CComBSTR :

 const wchar_t * pTest = ccbTest ? static_cast<BSTR>( ccbTest ) : L"null string"; 

I do not understand why a correction is necessary. I thought the compiler would just try to convert to BSTR on its own. Why is it temporary?

+5
source share
2 answers

Temporary exists for the same reasons this issue .

And as indicated in one of his answers :

The type of the triple ?: expression is the general type of its second and third argument. If both types are the same, you get a link back. If they are converted into each other, they are selected, and the other is converted [...]. Since you cannot return a reference to a temporary (transformed / advanced variable), its type is the type of value.

Since your L"null string" is temporary for a type other than CComBSTR , the entire result of the triple type is a value type, which means that the result is copied to temporary.

If you try:

 CComBSTR ccbTest( L"foo" ); CComBSTR ccbNull( L"ull string" ); const wchar_t * pTest = ccbTest ? ccbTest : ccbNull; 

No more temporary.

+2
source

I do not see a temporary CComBSTR in the above example.

CComBSTR is the RAII shell class used to control the BSTR's lifetime, and when it goes out of scope, the underlying BSTR will be destroyed.

ccbTest is an automatic (stack) variable, and when it goes out of scope (at the end of _tmain), it and the managed BSTR will be destroyed.

0
source

Source: https://habr.com/ru/post/1207751/


All Articles