重现问题的最少代码:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
CComBSTR ccbTest( L"foo" );
const wchar_t * pTest = ccbTest ? ccbTest : L"null string";
return 0;
}
当编译器想要在 pTest
中存储一个指针时,它会使用一个临时的 CComBSTR
。然后,它使用 CCcomBSTR
类中可用的 BSTR
转换,将指针存储在 pTest
中。然后临时文件被销毁,我在 pTest
中留下了一个悬空指针。
解决方法是转换 CComBSTR
:
const wchar_t * pTest = ccbTest ? static_cast<BSTR>( ccbTest ) : L"null string";
我不明白为什么需要修复。我认为编译器会尝试自行转换为 BSTR
。为什么是临时的?
最佳答案
临时存在的原因相同this question
如 one of its answer 中所述:
The type of the ternary ?: expression is the common type of its second and third argument. If both types are the same, you get a reference back. If they are convertable to each other, one gets chosen and the other gets converted [...]. Since you can't return an lvalue reference to a temporary (the converted / promoted variable), its type is a value type.
因为你的 L"null string"
是一个不同于 CComBSTR
的临时类型,所以三元的整个结果是一个值类型,这意味着结果被复制到一个临时的。
如果你尝试:
CComBSTR ccbTest( L"foo" );
CComBSTR ccbNull( L"ull string" );
const wchar_t * pTest = ccbTest ? ccbTest : ccbNull;
没有更多的临时。
关于c++ - 为什么编译器要使用临时变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27153485/