Boost 的 find_first
algorithm 是 C 的 strstr()
的 boost 等效项,但为什么 haystack(搜索空间)作为 非常量 引用传入?匹配范围在单独的 iterator_range
对象中返回,因此这不是按引用输出的问题。
它阻止调用由 make_iterator_range 创建的临时范围.
const std::string str("haystack");
const std::string findstr("stack");
boost::sub_range<const std::string> match = boost::algorithm::find_first(
boost::make_iterator_range(str),
boost::make_iterator_range(findstr));
相反,必须显式创建表示源范围的局部变量:
const std::string str("haystack");
const std::string findstr("stack");
boost::sub_range<const std::string> haystack = boost::make_iterator_range(str);
boost::sub_range<const std::string> match = boost::algorithm::find_first(
haystack,
boost::make_iterator_range(findstr));
(这同样适用于 boost/algorithm/string/find.hpp 中的其他函数,即 find
、ifind_first
、find_last
、ifind_last
、find_nth
、ifind_nth
、find_head
、find_tail
和 find_token
)。
最佳答案
这是为了确保调用find_first
后返回的范围仍然有效。
虽然上面的初始情况没问题,但以下情况将导致指向已销毁的临时字符串的匹配
:
boost::sub_range<const std::string> match = boost::algorithm::find_first(
boost::make_iterator_range(std::string("haystack"),
boost::make_iterator_range(std::string("stack"));
haystack 是非常量的要求阻止它绑定(bind)到一个临时对象(右值),该对象在 find_first
返回时被销毁并使 match
无效迭代器。
关于c++ - 为什么 boost::find_first 对其输入采用非常量引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500163/