It is safe to use constructors in function parameters in C++?

356 views Asked by At

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).

1

There are 1 answers

5
Johan Kotlinski On BEST ANSWER

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.