【发布时间】:2021-09-15 10:43:06
【问题描述】:
根据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?
【问题讨论】:
-
我的快速猜测:由于
regex_match()是一个重载函数,变体根本不返回匹配结果。因此,布尔值被用作返回值。 -
核心指南没有将任何东西描述为代码异味。在这种情况下,他们建议首选返回值而不是输出参数。该措辞并不意味着“你不应该......” - 它的意思是“使用返回值,除非你有特定的理由使用输出参数”。在您选择的情况下,原因是该函数向用户返回了不止一种类型的输出 - 并且他们选择返回
bool(以指示是否找到匹配项)。除其他外,避免强制调用者进行相对昂贵的检查,如果匹配集(输出参数)为空
标签: c++ regex output-parameter cpp-core-guidelines