在 C++ 中的函数参数中使用构造函数是否安全?

发布于 2025-01-01 12:10:41 字数 788 浏览 3 评论 0原文

此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你列表最软的妹 2025-01-08 12:10:41

我认为在第一种情况下,正则表达式被创建为临时对象,并将在匹配初始化后立即销毁。它需要有一个在整个循环中扩展的生命周期。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文