为什么 C++ 正则表达式函数使用输出参数?

问题描述

根据core guidelines,C++ 中的输出参数通常被认为是代码异味。然而,我们在 regular expressions library

中有这样的函数
template< class BidirIt,class Alloc,class CharT,class Traits >
bool regex_match( BidirIt first,BidirIt last,std::match_results<BidirIt,Alloc>& m,const std::basic_regex<CharT,Traits>& e,std::regex_constants::match_flag_type flags =
                      std::regex_constants::match_default );

其中 m输出参数。此处是否有违反核心准则而不是简单地按值返回 std::match_results 的具体原因?

解决方法

也有一些例外:

  • 对于非值类型,例如继承层次结构中的类型,通过 unique_ptr 或 shared_ptr 返回对象。
  • 如果一个类型的移动开销很大(例如,数组),考虑将它分配到空闲存储并返回一个句柄(例如,unique_ptr),或者将它传递给非常量的引用要填充的目标对象(用作输出参数)。
  • 要在内部循环中多次调用函数时重用承载容量的对象(例如 std::string、std::vector):将其视为输入/输出参数并按引用传递。

我认为这是 regxr 匹配的第二种情况。