c++ - 为什么 boost::find_first 对其输入采用非常量引用?

标签 c++ string boost

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 中的其他函数,即 findifind_firstfind_lastifind_lastfind_nthifind_nthfind_headfind_tailfind_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/

相关文章:

c++ - 经过一段时间后,是否有办法从流程中分离流程?

c++ - 如果 lambda 在运行时被移动/销毁会怎样?

java - 为什么它在字符串中返回错误的重复次数?

c++ - 如何比较两个不同大小的字符串

c++ - 除非在 target_link_directories() 命令上调用 pthread,否则 CMake 构建失败

c++ - boost 中的模板无效元函数

c++ - 跨平台 C++ 网络服务器库

c++ - 找不到 FinishMonsterBuffer() 方法

java - 检查给定的字符串是否可以由给定的一组字符串组成

c++ - boost::thread & 成员函数