Inspect the following code. Convince yourself that the expected output
should be
. Compile and test the code. The output
is unpredictable (may be similar to
depending on the machine and
circumstances). How do you explain this bug? How can you fix it?
#include<iostream> #include<vector> class ValueContainer { public: ValueContainer() : theInt(0) { } ~ValueContainer() { } void set(int* t) { theInt = t; } int get(void) { return *theInt; } private: int* theInt; }; ValueContainer* createContainer(int i) { ValueContainer* ret = new ValueContainer; ret->set(&i); return ret; } const int vecSize = 5; int main(int argc, char** argv) { using namespace std; vector<ValueContainer*> value; for(int i = 0; i < vecSize; i++) { value.push_back(createContainer(i)); } for(int i = 0; i < vecSize; i++) { cout << value[i]->get() << " "; } cout << endl; for(int i = 0; i < vecSize; i++) { delete value[i]; } return 0; }