这段代码有问题,但我找不到导致它的原因。
bool Parser::validateName(std::string name) {
int pos = name.find(INVALID_CHARS); //pos is -1,
bool result = ((name.find(INVALID_CHARS)) < 0); //result is false
//That was weird, does that imply that -1 >= 0?, let's see
result = (pos < 0) //result is true
result = ((name.find(INVALID_CHARS)) == -1) //result is true
result = (-1 < 0) //result is true
...
}
为什么第二行的结果为假。有什么我没有看到的吗?
std::string::find
返回类型为 std::string::size_type
的 std::string::npos
,定义为定义的无符号整数实现。无符号整数永远不会小于 0
。
您应该始终与std::string::npos
进行比较,以检查std::string::find
是否发现了某些东西。
std::string::find
在找不到请求的项目时返回std::string::npos
。根据标准(§ 21.4/5):
static const size_type npos = -1;
但是看到string::size_type
通常是unsigned int
的;这意味着-1
被转换成它的无符号等价物。通常,0xFFFF,这是unsigned int
的最大值。
在第二行中:
bool result = ((name.find(INVALID_CHARS)) < 0);
您正在比较两个unsigned int
值(0xFFFF 和 0),因此这将返回 false
。另一方面,在你的第四行:
result = ((name.find(INVALID_CHARS)) == -1)
你有一个unsigned int
和一个int
,所以提升规则适用,unsigned int
被转换成一个int
;正如我们之前看到的,npos
的有符号等价物总是-1,所以这返回true
。