为什么C ++ regex_match函数要求在该函数之外定义搜索字符串? [英] Why does the c++ regex_match function require the search string to be defined outside of the function?
问题描述
我正在使用Visual Studio 2013进行开发,该版本使用Microsoft C ++编译器工具的v12.
以下代码可以正常执行,将"foo"打印到控制台:
I am using Visual Studio 2013 for development, which uses v12 of Microsoft's c++ compiler tools.
The following code executes fine, printing "foo" to the console:
#include <regex>
#include <iostream>
#include <string>
std::string get() {
return std::string("foo bar");
}
int main() {
std::smatch matches;
std::string s = get();
std::regex_match(s, matches, std::regex("^(foo).*"));
std::cout << matches[1] << std::endl;
}
// Works as expected.
相同的代码,用字符串"s"代替"get()"函数,在运行时抛出字符串迭代器不兼容"错误:
The same code, with the string "s" substituted for the "get()" function, throws a "string iterators incompatible" error at runtime:
#include <regex>
#include <iostream>
#include <string>
std::string get() {
return std::string("foo bar");
}
int main() {
std::smatch matches;
std::regex_match(get(), matches, std::regex("^(foo).*"));
std::cout << matches[1] << std::endl;
}
// Debug Assertion Failed!
// Expression: string iterators incompatible
这对我来说毫无意义.谁能解释为什么会这样?
This makes no sense to me. Can anyone explain why this happens?
推荐答案
原因是 get()
返回一个临时字符串,因此匹配结果将迭代器包含到不再存在的对象中,尝试使用它们是不确定的行为.Visual Studio C ++库中的调试声明会注意到此问题并中止您的程序.
The reason is that get()
returns a temporary string, so the match results contains iterators into an object that no longer exists, and trying to use them is undefined behaviour. The debugging assertions in the Visual Studio C++ library notice this problem and abort your program.
最初,C ++ 11确实允许您尝试执行操作,但是由于它是如此危险,因此通过添加已删除的 std :: regex_match
重载来防止它被阻止,该重载在尝试执行时会被使用.要从临时字符串中获取匹配结果,请参见 LWG DR 2329 .这意味着您的程序不应在C ++ 14中编译(或在以C ++ 11模式实现DR的编译器中).GCC尚未实施更改,我会解决.
Originally C++11 did allow what you're trying to do, but because it is so dangerous it was prevented by adding a deleted overload of std::regex_match
which gets used when trying to get match results from a temporary string, see LWG DR 2329. That means your program should not compile in C++14 (or in compilers that implement the DR in C++11 mode too). GCC does not yet implement the change yet, I'll fix that.
这篇关于为什么C ++ regex_match函数要求在该函数之外定义搜索字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!