Consider the following snippet
class ItrTest {
private:
std::map<int, long> testMap;
std::map<int, long>::iterator itr;
public:
ItrTest(std::map<int, long> testMap): testMap(testMap) {
itr = testMap.begin();
}
void printNext() {
// itr = testMap.begin();
for (; itr != testMap.end(); itr++) {
cout<<"Key: "<<itr->first<<" Value:"<<itr->second<<endl;
}
}
};
int main() {
std::map<int, long> m{
{ 0, 100l },
{ 1, 200l },
{ 2, 300l },
{ 3, 400l },
{ 4, 500l },
};
ItrTest t(std::move(m));
t.printNext();
}
This throws a segmentation fault when trying to access the values inside the iterator. It is obvious this happens because the iterator becomes invalid (for me after a couple of iterations. Maybe it behaves differently on different systems). If I uncomment the first line of the function printNext() it works fine. I would like to get an explanation for this behaviour.
testMap(testMap)?! Why would anyone do that?!