此 C++ 代码在 Visual Studio 2010 中失败:
const sregex_iterator end;
for (sregex_iterator match(origString.begin(), origString.end(), regex(regExPattern)); match != end; ++match)
{
useMatch(*match);
}
在第一个循环之后,在第一个迭代器增量 (operator++
) 中,调试器失败,表明 regex_iterator 是“孤立的”。
我注意到可疑的正则表达式构造函数(我从某处复制了该片段)并尝试这样做:
const sregex_iterator end;
regex regexObj(regExPattern);
for (sregex_iterator match(origString.begin(), origString.end(), regexObj); match != end; ++match)
{
useMatch(*match);
}
这非常有效。
但是,为什么第一次尝试失败了?我认为它必须与 for
作用域或可能与内联构造函数以及迭代器构造函数中的 regex 参数是引用的事实......
但是,正如我前段时间在 stackoverflow 上读到的,我只记得我理解的东西,我想知道在 C++ 中使用构造函数作为函数参数是否安全(不使用 new
,当然)。
最佳答案
我想在第一种情况下,regex 被创建为一个临时对象,将在 match 初始化后立即销毁。它需要有一个在整个循环中扩展的生命周期。
关于c++ - 在 C++ 中的函数参数中使用构造函数是安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9094224/