繁体   English   中英

为什么boost :: find_first对其输入采用非const引用?

[英]Why does boost::find_first take a non-const reference to its input?

Boost的find_first算法相当于C的strstr() ,但为什么haystack - 搜索空间 - 作为非const引用传入? 匹配范围在单独的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之后返回的范围仍然有效。

虽然上面的初始情况可以正常,但以下将导致match指向已销毁的临时字符串:

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为非const的要求阻止它绑定到临时对象(rvalue),该对象在find_first返回时被销毁并使match的迭代器无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM