这段代码有问题,但我找不到导致它的原因。
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
...
}
为什么第二行的结果为false。有没有我没见过的东西?
答案 0 :(得分:9)
std::string::find
返回类型为std::string::npos
的{{1}},它被定义为实现定义的无符号整数。无符号整数决不会小于std::string::size_type
。
您应始终与0
进行比较,以检查std::string::npos
是否找到了某些内容。
答案 1 :(得分:2)
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
。