While I was using STL vector to store class objects,, I observed a very weird side effect, where push_back method modifies the Existing Data!
Basically I have a class containing several fields as follows:
class MyClass {
MyClass(std::string s, int i) {
StringValue = s;
IntValue = i;
}
std::string StringValue;
int IntValue;
}
I have a vector that contains the POINTERS to MyClass objects.. and then I am basically pushing back references to objects:
std::vector<MyClass*> MyVector;
MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);
MyVector.push_back(&c1);
// Result:
// *MyVector[0] ==> ("Class 1", 1)
MyVector.push_back(&c2);
// Result:
// *MyVector[0] ==> ("Class 2", 2) ??why 2??
// *MyVector[1] ==> ("Class 2", 2)
Do you see the strange result that I got?? I've set breakpoints after each push_back statement,,, and this weird thing happened.
The first push_back statement worked fine. But then the second push_back statement MODIFIED the content of the first element, which doesn't make sense to me..
I'm assuming that it has something to do with me storing References instead of actual objects inside the vector.... but I can't figure out what is wrong.
How can I handle this issue? Any insights?
Thanks
UPDATE:
(simplified code)
MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);
MyClass temp;
while (int i=0; i<2; i++) {
temp = c1;
MyVector.push_back(temp);
}
You guys are right,, I get what I'm doing wrong here.. The actual object gets destructed in every loop.. What's the best way to fix this while keeping the current structure?? I'ts hard to explain but I would like to keep this structure (keeping temporary buffer outside the loop).. is this possible?