
Hello, this is my my first post to a newsgroup, so i hope it will work... I use the boost regex library, and i was wondereing, why the following code doesn't work. When i output the result of the match, it should output "a", but it didn't, the output was something wrong like "yl". I figured out, that the reasen for this is, that the string sSearchString is just in the scope of the try-block, so it is allready destroyed when i do the output. If i put the declaration of the string above the try block, all works fine, because the searchstring is still existing when i do the output. The matchresult seems to save just a reference to the string. Am i doing sth wrong? I think this is quite dangerous, or is there a way to do this more safe? Thanx, Tobi /////////////////////////////////////////// boost::smatch match; // Match-Ergebnis bool bMatched; try { // Regulaeren Ausdruck anlegen boost::regex sExpr; sExpr.assign( "." ); // Suchstring anlegen std::string sSearchString = "abcdef"; // Matchen bMatched = boost::regex_search(sSearchString,match,sExpr); } catch(runtime_error& er) { m_sLog = er.what(); return; } if( bMatched ) { cout << match[0] << endl; } ///////////////////////////////////////////

this is my my first post to a newsgroup, so i hope it will work... I use the boost regex library, and i was wondereing, why the following code doesn't work. When i output the result of the match, it should output "a", but it didn't, the output was something wrong like "yl". I figured out, that the reasen for this is, that the string sSearchString is just in the scope of the try-block, so it is allready destroyed when i do the output. If i put the declaration of the string above the try block, all works fine, because the searchstring is still existing when i do the output. The matchresult seems to save just a reference to the string. Am i doing sth wrong? I think this is quite dangerous, or is there a way to do this more safe?
It's not a reference: the match_results stores *a pair of iterators* into the string being searched. These are valid only for as long as the string from which they originate is both valid *and unmodified*. This is standard iterator behaviour, and I suggest you read up on the STL and iterators if you're not familiar with these already. The alternative - storing a copy of the string - is both hugely expensive in comparison, and throws away important positional information. If you want to keep around the strings that matched, it's up to you to copy them. Regards, John.
participants (2)
-
John Maddock
-
Tobi