c++ - 为什么编译器要使用临时变量?

标签 c++ visual-studio-2010 atl ternary-operator bstr

重现问题的最少代码:

#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/

相关文章:

c++ - END_COM_MAP 中 IUnknown 成员函数的用途是什么?

c++ - g++ 和文件读取,Xcode/Snow Leopard 的奇怪行为

c# - Visual Studio、Razor、BuildProviders 和 Intellisense

c++ - 实现COM接口(interface) C++/VC++ 6.0/MFC

c++ - 等同于 MFC 窗口的 OnFinalMessage?

c# - 在我的应用程序中编辑 docx 的 asp.net + c# 技巧

c++ - 检查 CUDA 存在的程序需要 CUDA?

c++ - gcc C++14 与 msvc++ 2015 中的级联宏

c++ - Intellisense 不适用于 Visual Studio 2017 中的 cmake 项目

c# - 在 Visual Studio 2010 中设计报表的教程?