对于空输入字符串,string::find的行为是否定义良好?

c++: Is the behavior of string::find for empty input string well defined

本文关键字:是否 定义 find 输入 于空 字符串 string      更新时间:2023-10-16

下面的代码片段在我的编译器(visual studio)上总是返回true。但是这种行为定义良好并且可移植吗?

bool return_always_true(std::string const& str)
{
    return str.find("") != std::string::npos;
}
int main(){
     cout << boolapha << return_always_true("") << endl
          << return_always_true("oxylottl") << endl
          << return_always_true("lorem ipsum") << endl;
 //true true true
}

我发现cppreference.com比标准网站更容易阅读。引用:

查找第一个子字符串等于str

形式上,如果满足以下所有条件,则子串str在位置xpos上被找到:

  1. xpos >= pos
  2. xpos + str.size() <= size()
  3. 适用于str, Traits::eq(at(xpos+n), str.at(n))中所有位置n

空字符串总是匹配目标字符串的开头,因为

  1. 0>= 0
  2. 0+0 <= size()
  3. 没有位置是str,所以匹配条件为空真。

是:"当且仅当pos <= size()时在pos处找到空子字符串"

根据Cppreference:

  • 当且仅当pos <= size()

str.find("")使用std::basic_string::find的第三个重载,其签名为:

size_type find( const CharT* s, size_type pos = 0 ) const;

这意味着pos0开始,所以pos <= size()总是为真。