Hi All,
I have a situation in my code where by during iteration of my vector of pointers, I am modifying the original container. I have done some research and learned this causes a crash (I Think)... The problem I am facing is illustrated in my test program as follows:
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
struct Test1
{
void update(){
cout << "update from Test1" << endl;
}
};
struct Test
{
vector<shared_ptr<Test1>> m_test;
void pushOn(std::shared_ptr<Test1> &test1)
{
m_test.push_back(test1);
}
void update()
{
for (vector<shared_ptr<Test1>>::reverse_iterator i = m_test.rbegin(); i != m_test.rend(); ++i)
{
auto newPtr = make_shared<Test1>();
(*i)->update();
pushOn(newPtr);
cout << "if you read this it passed" << endl;
}
}
};
int main()
{
auto TestClass = make_shared<Test>();
auto aaa = make_shared<Test1>();
TestClass->pushOn(aaa);
TestClass->update();
getchar();
return 0;
}
If you run the program with pushOn(newPtr); commended out, then it works, otherwise it crashes.
I have some questions.
1. May I have some advice on how to fix this?
2. If I am encountering this, does that mean a fundamentally flawed program design?
Thanks