I'm trying to construct an sregex_iterator from some complicated computations so I wrote a function to do this and return the iterator. However when I then want to increment the returned iterator, the program crashes, sometimes throwing std::bad_alloc, sometimes not..
I managed to reduce it to a MWE with little code but somehow I still cannot figure out what is happening..
#include <iostream>
#include <regex>
using namespace std;
sregex_iterator get_it(const string& str) {
regex r("([ab]{3})");
auto it = sregex_iterator(str.begin(), str.end(), r);
cout << (it == sregex_iterator() ? "end\n" : "more\n");
++it; //works as expected .. no crash. When commented out, program still crashes
cout << "can incr ..\n";
return it;
}
int main(int argc, char** argv) {
auto it = get_it("aaa bbb");
cout << (it == sregex_iterator() ? "end\n" : "more\n");
++it; //this crashes the program
cout << "success\n"; // never runs
}
To compile I use g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0 with -std=c++11
flag.
This runs and outputs
more
can incr ..
more
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
So increment works in the function where I construct the iterator, but not outside. But all that happens is copy (/move if RVO happens) of the iterator, which should not invalidate it? Surely the sregex_iterator
does not store reference or pointer to any of its constructed-from arguments?
My only guess is there must be a ref/ptr to temporary somewhere but I do not see it.. or what am I missing here?
Aucun commentaire:
Enregistrer un commentaire