rub*_*nvb 3 c++ compiler-warnings visual-c++
我刚刚安装了Windows SDK v7.1(MSVC 10.0)并运行了我的代码(几乎)完全警告级别(W3,默认为qmake CONFIG += warn_on)并且对于警告感到惊讶C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
在下面的代码中,stream是std::istream和token是std::string.
// in some function returning bool
return (stream >> token) // triggers warning c4800:
// '(void *)': forcing value to bool 'true' or 'false' (performance warning)`
// somewhere else
if( stream >> token ) // does not trigger warning c4800
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我甚至不知道为什么首先触发警告.我认为第一段代码已经返回了bool.
我明白这是挑剔,警告甚至不应该存在,但它是我的代码中唯一一个MSVC /W3和gcc 之间-Wall -pedantic,所以我想知道:)
小更新:我知道警告旨在让你知道你正在假设int-> bool转换,但是1)为什么你甚至仍然使用bool(== 为什么typedef int大多数)和2)if(2)不转换2为true或是的,我认为这是一个谓词的全部概念,无论是真还是假.
What is going on here? I don't even get why the warning is triggered in the first place. I thought the first bit of code already returned a bool anyways.
Streams have an implicit conversion operator that returns a void*. (That's a version of the safe bool idiom. It's done this way because there is less contexts in which void* compiles than bool, so there's less contexts in which the implicit conversion could kick in unwanted.)[1]
Streams' operator>>() returns a reference to its left operand - the stream. That's so you can chain input operations: strm >> value1 >> value2 is executed as ((strm >> value1) >> value2).
现在,当你说if( strm >> value ),strm >> value执行并返回一个流.为了将它放入if语句中,执行隐式转换void*,然后检查该指针是否存在NULL.
这没有什么不同if(ptr),if声明隐含地将其条件转换为bool,但编译器永远不会对此发出警告,因为条件不是bool如此常见.
随着return,这是不同的.如果要返回某种类型,通常返回的表达式应为该类型.VC的警告很烦人,对我来说,在100次中有99次这是多余的.但剩下的1%(从来没有一个性能问题,BTW;我认为这个警告很愚蠢)让我很高兴警告就在那里.
The workaround for this warning is to
return 0 != <expression>
Run Code Online (Sandbox Code Playgroud)
where <expression> is whatever you think should be considered a boolean value.
[1] ISTR Stroustrup writing somewhere that an operator bool() would silently compile if you messed up the operators: ostrm >> 5; (note the >> instead of <<) would compile fine, but silently do the wrong thing. (It converts the boolean to an integer and right-shifts that 5 times, then discard the value.)
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |