在 C++ 中的函数参数中使用构造函数是否安全?
此 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
范围一起使用,或者可能与内联构造函数一起使用,并且迭代器构造函数中的正则表达式参数是一个引用...
但是,正如我前段时间在 stackoverflow 中读到的那样,我只记得我理解的东西,我想知道在C++中使用构造函数作为函数参数是否安全(当然不使用new
)。
This C++ code fails in Visual Studio 2010:
const sregex_iterator end;
for (sregex_iterator match(origString.begin(), origString.end(), regex(regExPattern)); match != end; ++match)
{
useMatch(*match);
}
After the first loop, in the first iterator increment (operator++
) the debugger fails indicating that the regex_iterator is "orphaned".
I noticed the dubious regex constructor (I copied the fragment from somewhere) and i tried with this:
const sregex_iterator end;
regex regexObj(regExPattern);
for (sregex_iterator match(origString.begin(), origString.end(), regexObj); match != end; ++match)
{
useMatch(*match);
}
This worked perfectly.
But, why is the first attempt failing? I suposse it has to be with the for
scope or maybe with the inlined constructor and the fact that the regex parameter in the iterator constructor is a reference...
But, as I read in stackoverflow some time ago, I remember only the things that I understand, and I would like to know if it is safe to use constructors as function parameters in C++ (without using new
, of course).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为在第一种情况下,正则表达式被创建为临时对象,并将在匹配初始化后立即销毁。它需要有一个在整个循环中扩展的生命周期。
I am thinking in the first case, regex is created as a temporary object and will be destroyed immediately after the initialization of match. It needs to have a lifetime that expands throughout the entire loop.