[英]Strange result from a C++/MFC compiler in VS 2008
I thought I knew VS 2008 C++ compiler really well: 我以为我非常了解VS 2008 C ++编译器:
CString str;
str.Empty();
LPCTSTR pStr = str.IsEmpty() ? NULL : str;
::MessageBox(NULL, pStr ? L"pStr is NOT null" : L"pStr is null", L"Result", MB_OK);
Can someone explain why am I getting this? 有人可以解释我为什么得到这个?
LPCTSTR pStr = str.IsEmpty() ? (LPCTSTR)NULL : str;
does return a NULL
. 确实返回
NULL
。
It looks like this happens because the two expressions are not of the same type; 看起来这是因为两个表达式的类型不同; MSDN Docs says
MSDN Docs说
If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type
如果两个表达式都是指针类型或者如果一个是指针类型而另一个是一个计算结果为0的常量表达式,则执行指针转换以将它们转换为通用类型
A quote from a MSDN forum post : 来自MSDN论坛帖子的引用:
5.16-3- in the standard describes the type coercion taking place here;
标准中的5.16-3-描述了此处发生的类型强制; the expression (B ? E1 : E2) can only have a single type, so if the types of expressions E1 and E2 are different, they must be coerced into a common, safe type before evaluation of either expression occurrs ... So, the type of E1 in this example is CString, and the type of E2 is int.
表达式(B?E1:E2)只能有一种类型,所以如果表达式E1和E2的类型不同,在评估任何一个表达式之前,它们必须被强制转换为一个通用的安全类型......所以,此示例中的E1类型为CString,E2的类型为int。 The process described in 5.16-3- eventually concludes that the only safe type for both of these to convert to is CString.
5.16-3中描述的过程最终得出结论,转换为这两者的唯一安全类型是CString。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.