Why do C++ regular expression functions use output parameters?

157 views Asked by At

Output parameters in C++ are generally considered a code smell according to the core guidelines. Yet, we have such functions in the 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 );

in which m is an output parameter. Is there a specific reason for breaking the core guidelines here and not simply returning the std::match_results by value?

1

There are 1 answers

0
Afshin On

There are some exceptions too:

  • For non-value types, such as types in an inheritance hierarchy, return the object by unique_ptr or shared_ptr.
  • If a type is expensive to move (e.g., array), consider allocating it on the free store and return a handle (e.g., unique_ptr), or passing it in a reference to non-const target object to fill (to be used as an out-parameter).
  • To reuse an object that carries capacity (e.g., std::string, std::vector) across multiple calls to the function in an inner loop: treat it as an in/out parameter and pass by reference.

I think it is the 2nd case for regxr match.