是否可以在多个线程中使用
std::regex
对象全部使用std::sregex_iterator
,std::regex_match
等?
例如,以下是否会产生逻辑行为:
bool SomeFunc( const std::string& szString1, const std::string& szString2 )
{
static const std::regex regexTest( "=== ([\\w]+) ===", std::regex_constants::optimize );
std::future<bool> f = std::async( []( std::string szString ) {
return std::regex_match( szString, regexTest );
}, szString1 );
bool b = std::regex_match( szString2, regexTest );
return (b && f.get());
}
我找不到任何说明使用const std::regex
同时导致未定义行为的内容。据我所知,没有对正则表达式对象进行编辑,因此不应该同时使用它来诱导未定义的行为?
提前致谢!
答案 0 :(得分:19)
是的,const std::regex
是线程安全的。实际上,标准库中的任何const方法都是线程安全的,请参阅:
§17.6.5.9/ 3。 C ++标准库函数不应直接或 间接修改除了以外的线程可访问的对象(1.10) 当前线程,除非直接或间接访问对象 通过函数的非const参数,包括这个。