Most examples using boost::regex_match
construct the boost::regex
object before calling match; e.g.
boost::regex pattern("(...)");
boost::smatch match;
if (boost::regex_match(text, match, pattern)) {
// use the match object here
}
(See https://github.com/boostorg/regex/tree/develop/example/snippets for other examples).
However, suppose I instead pass a temporary regex
object to regex_match
, e.g.
boost::smatch match;
if (boost::regex_match(text, match, boost::regex("(...)"))) {
// use the match object here
}
Is this code valid? That is, does the boost::regex
object need to live as long as the boost::smatch
object, or does that lifetime requirement only apply to the matched string? The code appears to work fine, but I'm worried that I may run into trouble if the smatch
object internally keeps a reference to the regular expression used for matching.
I couldn't find this explicitly documented at https://www.boost.org/doc/libs/1_79_0/libs/regex/doc/html/index.html, but it's possible I have missed it.
CodePudding user response:
Firstly, from a design perspective it wouldn't make sense to store a reference to boost::regex
in boost::smatch
.
Having a look at the implementation confirms that:
template <class BidiIterator, class Allocator>
class match_results
{
// ...
vector_type m_subs; // subexpressions
BidiIterator m_base; // where the search started from
sub_match<BidiIterator> m_null; // a null match
boost::shared_ptr<named_sub_type> m_named_subs; // Shared copy of named subs in the regex object
int m_last_closed_paren; // Last ) to be seen - used for formatting
bool m_is_singular; // True if our stored iterators are singular
};